ikuseiGmbH/smart-village-app-cms

View on GitHub
app/controllers/surveys_controller.rb

Summary

Maintainability
B
6 hrs
Test Coverage

Parameters should be whitelisted for mass assignment
Open

      @survey_params = params.require(:survey).permit!

Mass assignment is a feature of Rails which allows an application to create a record from the values of a hash.

Example:

User.new(params[:user])

Unfortunately, if there is a user field called admin which controls administrator access, now any user can make themselves an administrator.

attr_accessible and attr_protected can be used to limit mass assignment. However, Brakeman will warn unless attr_accessible is used, or mass assignment is completely disabled.

There are two different mass assignment warnings which can arise. The first is when mass assignment actually occurs, such as the example above. This results in a warning like

Unprotected mass assignment near line 61: User.new(params[:user])

The other warning is raised whenever a model is found which does not use attr_accessible. This produces generic warnings like

Mass assignment is not restricted using attr_accessible

with a list of affected models.

In Rails 3.1 and newer, mass assignment can easily be disabled:

config.active_record.whitelist_attributes = true

Unfortunately, it can also easily be bypassed:

User.new(params[:user], :without_protection => true)

Brakeman will warn on uses of without_protection.

Class has too many lines. [188/100]
Open

class SurveysController < ApplicationController
  before_action :verify_current_user
  before_action { verify_current_user_role("role_survey") }
  before_action :init_graphql_client

This cop checks if the length a class exceeds some maximum value. Comment lines can optionally be ignored. The maximum allowed length is configurable.

Method has too many lines. [57/10]
Open

    def edit_survey_record
      results = @smart_village.query <<~GRAPHQL
        query {
          surveys(
            ids: [

This cop checks if the length of a method exceeds some maximum value. Comment lines can optionally be ignored. The maximum allowed length is configurable.

Assignment Branch Condition size for edit_survey_record is too high. [34.06/15]
Open

    def edit_survey_record
      results = @smart_village.query <<~GRAPHQL
        query {
          surveys(
            ids: [

This cop checks that the ABC size of methods is not higher than the configured maximum. The ABC size is based on assignments, branches (method calls), and conditions. See http://c2.com/cgi/wiki?AbcMetric and https://en.wikipedia.org/wiki/ABC_Software_Metric.

Method has too many lines. [24/10]
Open

  def index
    results = @smart_village.query <<~GRAPHQL
      query {
        surveys {
          id

This cop checks if the length of a method exceeds some maximum value. Comment lines can optionally be ignored. The maximum allowed length is configurable.

Method has too many lines. [18/10]
Open

  def destroy
    results = @smart_village.query <<~GRAPHQL
      mutation {
        destroyRecord(
          id: #{params["id"]},

This cop checks if the length of a method exceeds some maximum value. Comment lines can optionally be ignored. The maximum allowed length is configurable.

Method has too many lines. [16/10]
Open

    def convert_params_for_graphql
      # Convert date, as we always have and need exactly one
      if @survey_params["dates"].present?
        dates = @survey_params.delete(:dates)
        @survey_params["date"] = dates["0"]

This cop checks if the length of a method exceeds some maximum value. Comment lines can optionally be ignored. The maximum allowed length is configurable.

Complex method SurveysController#edit_survey_record (44.4)
Open

    def edit_survey_record
      results = @smart_village.query <<~GRAPHQL
        query {
          surveys(
            ids: [
Severity: Minor
Found in app/controllers/surveys_controller.rb by flog

Flog calculates the ABC score for methods. The ABC score is based on assignments, branches (method calls), and conditions.

You can read more about ABC metrics or the flog tool

Method edit_survey_record has 57 lines of code (exceeds 25 allowed). Consider refactoring.
Open

    def edit_survey_record
      results = @smart_village.query <<~GRAPHQL
        query {
          surveys(
            ids: [
Severity: Major
Found in app/controllers/surveys_controller.rb - About 2 hrs to fix

    Assignment Branch Condition size for convert_params_for_graphql is too high. [18.81/15]
    Open

        def convert_params_for_graphql
          # Convert date, as we always have and need exactly one
          if @survey_params["dates"].present?
            dates = @survey_params.delete(:dates)
            @survey_params["date"] = dates["0"]

    This cop checks that the ABC size of methods is not higher than the configured maximum. The ABC size is based on assignments, branches (method calls), and conditions. See http://c2.com/cgi/wiki?AbcMetric and https://en.wikipedia.org/wiki/ABC_Software_Metric.

    Method has too many lines. [12/10]
    Open

      def update
        survey_id = params[:id]
        query = create_params
        begin
          @smart_village.query query

    This cop checks if the length of a method exceeds some maximum value. Comment lines can optionally be ignored. The maximum allowed length is configurable.

    Method has too many lines. [12/10]
    Open

      def create
        query = create_params
        begin
          results = @smart_village.query query
        rescue Graphlient::Errors::GraphQLError => e

    This cop checks if the length of a method exceeds some maximum value. Comment lines can optionally be ignored. The maximum allowed length is configurable.

    Assignment Branch Condition size for create is too high. [16.58/15]
    Open

      def create
        query = create_params
        begin
          results = @smart_village.query query
        rescue Graphlient::Errors::GraphQLError => e

    This cop checks that the ABC size of methods is not higher than the configured maximum. The ABC size is based on assignments, branches (method calls), and conditions. See http://c2.com/cgi/wiki?AbcMetric and https://en.wikipedia.org/wiki/ABC_Software_Metric.

    Method has too many lines. [11/10]
    Open

        def nested_values?(value_to_check, result = [])
          result << true if value_to_check.class == String && value_to_check.present?
    
          if value_to_check.class == Array
            value_to_check.each do |value|

    This cop checks if the length of a method exceeds some maximum value. Comment lines can optionally be ignored. The maximum allowed length is configurable.

    Assignment Branch Condition size for update is too high. [15.26/15]
    Open

      def update
        survey_id = params[:id]
        query = create_params
        begin
          @smart_village.query query

    This cop checks that the ABC size of methods is not higher than the configured maximum. The ABC size is based on assignments, branches (method calls), and conditions. See http://c2.com/cgi/wiki?AbcMetric and https://en.wikipedia.org/wiki/ABC_Software_Metric.

    Method convert_params_for_graphql has a Cognitive Complexity of 11 (exceeds 5 allowed). Consider refactoring.
    Open

        def convert_params_for_graphql
          # Convert date, as we always have and need exactly one
          if @survey_params["dates"].present?
            dates = @survey_params.delete(:dates)
            @survey_params["date"] = dates["0"]
    Severity: Minor
    Found in app/controllers/surveys_controller.rb - About 1 hr to fix

    Cognitive Complexity

    Cognitive Complexity is a measure of how difficult a unit of code is to intuitively understand. Unlike Cyclomatic Complexity, which determines how difficult your code will be to test, Cognitive Complexity tells you how difficult your code will be to read and comprehend.

    A method's cognitive complexity is based on a few simple rules:

    • Code is not considered more complex when it uses shorthand that the language provides for collapsing multiple statements into one
    • Code is considered more complex for each "break in the linear flow of the code"
    • Code is considered more complex when "flow breaking structures are nested"

    Further reading

    SurveysController#nested_values? has approx 6 statements
    Open

        def nested_values?(value_to_check, result = [])
    Severity: Minor
    Found in app/controllers/surveys_controller.rb by reek

    A method with Too Many Statements is any method that has a large number of lines.

    Too Many Statements warns about any method that has more than 5 statements. Reek's smell detector for Too Many Statements counts +1 for every simple statement in a method and +1 for every statement within a control structure (if, else, case, when, for, while, until, begin, rescue) but it doesn't count the control structure itself.

    So the following method would score +6 in Reek's statement-counting algorithm:

    def parse(arg, argv, &error)
      if !(val = arg) and (argv.empty? or /\A-/ =~ (val = argv[0]))
        return nil, block, nil                                         # +1
      end
      opt = (val = parse_arg(val, &error))[1]                          # +2
      val = conv_arg(*val)                                             # +3
      if opt and !arg
        argv.shift                                                     # +4
      else
        val[0] = nil                                                   # +5
      end
      val                                                              # +6
    end

    (You might argue that the two assigments within the first @if@ should count as statements, and that perhaps the nested assignment should count as +2.)

    SurveysController#create has approx 10 statements
    Open

      def create
    Severity: Minor
    Found in app/controllers/surveys_controller.rb by reek

    A method with Too Many Statements is any method that has a large number of lines.

    Too Many Statements warns about any method that has more than 5 statements. Reek's smell detector for Too Many Statements counts +1 for every simple statement in a method and +1 for every statement within a control structure (if, else, case, when, for, while, until, begin, rescue) but it doesn't count the control structure itself.

    So the following method would score +6 in Reek's statement-counting algorithm:

    def parse(arg, argv, &error)
      if !(val = arg) and (argv.empty? or /\A-/ =~ (val = argv[0]))
        return nil, block, nil                                         # +1
      end
      opt = (val = parse_arg(val, &error))[1]                          # +2
      val = conv_arg(*val)                                             # +3
      if opt and !arg
        argv.shift                                                     # +4
      else
        val[0] = nil                                                   # +5
      end
      val                                                              # +6
    end

    (You might argue that the two assigments within the first @if@ should count as statements, and that perhaps the nested assignment should count as +2.)

    SurveysController#convert_params_for_graphql has approx 11 statements
    Open

        def convert_params_for_graphql
    Severity: Minor
    Found in app/controllers/surveys_controller.rb by reek

    A method with Too Many Statements is any method that has a large number of lines.

    Too Many Statements warns about any method that has more than 5 statements. Reek's smell detector for Too Many Statements counts +1 for every simple statement in a method and +1 for every statement within a control structure (if, else, case, when, for, while, until, begin, rescue) but it doesn't count the control structure itself.

    So the following method would score +6 in Reek's statement-counting algorithm:

    def parse(arg, argv, &error)
      if !(val = arg) and (argv.empty? or /\A-/ =~ (val = argv[0]))
        return nil, block, nil                                         # +1
      end
      opt = (val = parse_arg(val, &error))[1]                          # +2
      val = conv_arg(*val)                                             # +3
      if opt and !arg
        argv.shift                                                     # +4
      else
        val[0] = nil                                                   # +5
      end
      val                                                              # +6
    end

    (You might argue that the two assigments within the first @if@ should count as statements, and that perhaps the nested assignment should count as +2.)

    SurveysController#nested_values? refers to 'value_to_check' more than self (maybe move it to another class?)
    Open

          result << true if value_to_check.class == String && value_to_check.present?
    
          if value_to_check.class == Array
            value_to_check.each do |value|
              nested_values?(value, result)
    Severity: Minor
    Found in app/controllers/surveys_controller.rb by reek

    Feature Envy occurs when a code fragment references another object more often than it references itself, or when several clients do the same series of manipulations on a particular type of object.

    Feature Envy reduces the code's ability to communicate intent: code that "belongs" on one class but which is located in another can be hard to find, and may upset the "System of Names" in the host class.

    Feature Envy also affects the design's flexibility: A code fragment that is in the wrong class creates couplings that may not be natural within the application's domain, and creates a loss of cohesion in the unwilling host class.

    Feature Envy often arises because it must manipulate other objects (usually its arguments) to get them into a useful form, and one force preventing them (the arguments) doing this themselves is that the common knowledge lives outside the arguments, or the arguments are of too basic a type to justify extending that type. Therefore there must be something which 'knows' about the contents or purposes of the arguments. That thing would have to be more than just a basic type, because the basic types are either containers which don't know about their contents, or they are single objects which can't capture their relationship with their fellows of the same type. So, this thing with the extra knowledge should be reified into a class, and the utility method will most likely belong there.

    Example

    Running Reek on:

    class Warehouse
      def sale_price(item)
        (item.price - item.rebate) * @vat
      end
    end

    would report:

    Warehouse#total_price refers to item more than self (FeatureEnvy)

    since this:

    (item.price - item.rebate)

    belongs to the Item class, not the Warehouse.

    SurveysController#update has approx 10 statements
    Open

      def update
    Severity: Minor
    Found in app/controllers/surveys_controller.rb by reek

    A method with Too Many Statements is any method that has a large number of lines.

    Too Many Statements warns about any method that has more than 5 statements. Reek's smell detector for Too Many Statements counts +1 for every simple statement in a method and +1 for every statement within a control structure (if, else, case, when, for, while, until, begin, rescue) but it doesn't count the control structure itself.

    So the following method would score +6 in Reek's statement-counting algorithm:

    def parse(arg, argv, &error)
      if !(val = arg) and (argv.empty? or /\A-/ =~ (val = argv[0]))
        return nil, block, nil                                         # +1
      end
      opt = (val = parse_arg(val, &error))[1]                          # +2
      val = conv_arg(*val)                                             # +3
      if opt and !arg
        argv.shift                                                     # +4
      else
        val[0] = nil                                                   # +5
      end
      val                                                              # +6
    end

    (You might argue that the two assigments within the first @if@ should count as statements, and that perhaps the nested assignment should count as +2.)

    SurveysController#edit_survey_record refers to 'survey' more than self (maybe move it to another class?)
    Open

            id: survey.id,
            title_de: survey.title["de"],
            title_pl: survey.title["pl"],
            description_de: survey.description["de"],
            description_pl: survey.description["pl"],
    Severity: Minor
    Found in app/controllers/surveys_controller.rb by reek

    Feature Envy occurs when a code fragment references another object more often than it references itself, or when several clients do the same series of manipulations on a particular type of object.

    Feature Envy reduces the code's ability to communicate intent: code that "belongs" on one class but which is located in another can be hard to find, and may upset the "System of Names" in the host class.

    Feature Envy also affects the design's flexibility: A code fragment that is in the wrong class creates couplings that may not be natural within the application's domain, and creates a loss of cohesion in the unwilling host class.

    Feature Envy often arises because it must manipulate other objects (usually its arguments) to get them into a useful form, and one force preventing them (the arguments) doing this themselves is that the common knowledge lives outside the arguments, or the arguments are of too basic a type to justify extending that type. Therefore there must be something which 'knows' about the contents or purposes of the arguments. That thing would have to be more than just a basic type, because the basic types are either containers which don't know about their contents, or they are single objects which can't capture their relationship with their fellows of the same type. So, this thing with the extra knowledge should be reified into a class, and the utility method will most likely belong there.

    Example

    Running Reek on:

    class Warehouse
      def sale_price(item)
        (item.price - item.rebate) * @vat
      end
    end

    would report:

    Warehouse#total_price refers to item more than self (FeatureEnvy)

    since this:

    (item.price - item.rebate)

    belongs to the Item class, not the Warehouse.

    Complex method SurveysController#convert_params_for_graphql (25.6)
    Open

        def convert_params_for_graphql
          # Convert date, as we always have and need exactly one
          if @survey_params["dates"].present?
            dates = @survey_params.delete(:dates)
            @survey_params["date"] = dates["0"]
    Severity: Minor
    Found in app/controllers/surveys_controller.rb by flog

    Flog calculates the ABC score for methods. The ABC score is based on assignments, branches (method calls), and conditions.

    You can read more about ABC metrics or the flog tool

    SurveysController#nested_values? calls 'value_to_check.each' 2 times
    Open

            value_to_check.each do |value|
              nested_values?(value, result)
            end
          elsif value_to_check.class.to_s.include?("Hash")
            value_to_check.each do |_key, value|
    Severity: Minor
    Found in app/controllers/surveys_controller.rb by reek

    Duplication occurs when two fragments of code look nearly identical, or when two fragments of code have nearly identical effects at some conceptual level.

    Reek implements a check for Duplicate Method Call.

    Example

    Here's a very much simplified and contrived example. The following method will report a warning:

    def double_thing()
      @other.thing + @other.thing
    end

    One quick approach to silence Reek would be to refactor the code thus:

    def double_thing()
      thing = @other.thing
      thing + thing
    end

    A slightly different approach would be to replace all calls of double_thing by calls to @other.double_thing:

    class Other
      def double_thing()
        thing + thing
      end
    end

    The approach you take will depend on balancing other factors in your code.

    SurveysController#convert_params_for_graphql calls '@survey_params["response_options"]' 2 times
    Open

          if @survey_params["response_options"].present?
            response_options = []
            @survey_params["response_options"].each do |_key, response_option|
    Severity: Minor
    Found in app/controllers/surveys_controller.rb by reek

    Duplication occurs when two fragments of code look nearly identical, or when two fragments of code have nearly identical effects at some conceptual level.

    Reek implements a check for Duplicate Method Call.

    Example

    Here's a very much simplified and contrived example. The following method will report a warning:

    def double_thing()
      @other.thing + @other.thing
    end

    One quick approach to silence Reek would be to refactor the code thus:

    def double_thing()
      thing = @other.thing
      thing + thing
    end

    A slightly different approach would be to replace all calls of double_thing by calls to @other.double_thing:

    class Other
      def double_thing()
        thing + thing
      end
    end

    The approach you take will depend on balancing other factors in your code.

    SurveysController has no descriptive comment
    Open

    class SurveysController < ApplicationController
    Severity: Minor
    Found in app/controllers/surveys_controller.rb by reek

    Classes and modules are the units of reuse and release. It is therefore considered good practice to annotate every class and module with a brief comment outlining its responsibilities.

    Example

    Given

    class Dummy
      # Do things...
    end

    Reek would emit the following warning:

    test.rb -- 1 warning:
      [1]:Dummy has no descriptive comment (IrresponsibleModule)

    Fixing this is simple - just an explaining comment:

    # The Dummy class is responsible for ...
    class Dummy
      # Do things...
    end

    SurveysController assumes too much for instance variable '@smart_village'
    Open

    class SurveysController < ApplicationController
    Severity: Minor
    Found in app/controllers/surveys_controller.rb by reek

    Classes should not assume that instance variables are set or present outside of the current class definition.

    Good:

    class Foo
      def initialize
        @bar = :foo
      end
    
      def foo?
        @bar == :foo
      end
    end

    Good as well:

    class Foo
      def foo?
        bar == :foo
      end
    
      def bar
        @bar ||= :foo
      end
    end

    Bad:

    class Foo
      def go_foo!
        @bar = :foo
      end
    
      def foo?
        @bar == :foo
      end
    end

    Example

    Running Reek on:

    class Dummy
      def test
        @ivar
      end
    end

    would report:

    [1]:InstanceVariableAssumption: Dummy assumes too much for instance variable @ivar

    Note that this example would trigger this smell warning as well:

    class Parent
      def initialize(omg)
        @omg = omg
      end
    end
    
    class Child < Parent
      def foo
        @omg
      end
    end

    The way to address the smell warning is that you should create an attr_reader to use @omg in the subclass and not access @omg directly like this:

    class Parent
      attr_reader :omg
    
      def initialize(omg)
        @omg = omg
      end
    end
    
    class Child < Parent
      def foo
        omg
      end
    end

    Directly accessing instance variables is considered a smell because it breaks encapsulation and makes it harder to reason about code.

    If you don't want to expose those methods as public API just make them private like this:

    class Parent
      def initialize(omg)
        @omg = omg
      end
    
      private
      attr_reader :omg
    end
    
    class Child < Parent
      def foo
        omg
      end
    end

    Current Support in Reek

    An instance variable must:

    • be set in the constructor
    • or be accessed through a method with lazy initialization / memoization.

    If not, Instance Variable Assumption will be reported.

    SurveysController#nested_values? calls 'nested_values?(value, result)' 2 times
    Open

              nested_values?(value, result)
            end
          elsif value_to_check.class.to_s.include?("Hash")
            value_to_check.each do |_key, value|
              nested_values?(value, result)
    Severity: Minor
    Found in app/controllers/surveys_controller.rb by reek

    Duplication occurs when two fragments of code look nearly identical, or when two fragments of code have nearly identical effects at some conceptual level.

    Reek implements a check for Duplicate Method Call.

    Example

    Here's a very much simplified and contrived example. The following method will report a warning:

    def double_thing()
      @other.thing + @other.thing
    end

    One quick approach to silence Reek would be to refactor the code thus:

    def double_thing()
      thing = @other.thing
      thing + thing
    end

    A slightly different approach would be to replace all calls of double_thing by calls to @other.double_thing:

    class Other
      def double_thing()
        thing + thing
      end
    end

    The approach you take will depend on balancing other factors in your code.

    SurveysController#edit_survey_record calls 'survey.title' 2 times
    Open

            title_de: survey.title["de"],
            title_pl: survey.title["pl"],
    Severity: Minor
    Found in app/controllers/surveys_controller.rb by reek

    Duplication occurs when two fragments of code look nearly identical, or when two fragments of code have nearly identical effects at some conceptual level.

    Reek implements a check for Duplicate Method Call.

    Example

    Here's a very much simplified and contrived example. The following method will report a warning:

    def double_thing()
      @other.thing + @other.thing
    end

    One quick approach to silence Reek would be to refactor the code thus:

    def double_thing()
      thing = @other.thing
      thing + thing
    end

    A slightly different approach would be to replace all calls of double_thing by calls to @other.double_thing:

    class Other
      def double_thing()
        thing + thing
      end
    end

    The approach you take will depend on balancing other factors in your code.

    SurveysController#edit_survey_record calls 'survey.description' 2 times
    Open

            description_de: survey.description["de"],
            description_pl: survey.description["pl"],
    Severity: Minor
    Found in app/controllers/surveys_controller.rb by reek

    Duplication occurs when two fragments of code look nearly identical, or when two fragments of code have nearly identical effects at some conceptual level.

    Reek implements a check for Duplicate Method Call.

    Example

    Here's a very much simplified and contrived example. The following method will report a warning:

    def double_thing()
      @other.thing + @other.thing
    end

    One quick approach to silence Reek would be to refactor the code thus:

    def double_thing()
      thing = @other.thing
      thing + thing
    end

    A slightly different approach would be to replace all calls of double_thing by calls to @other.double_thing:

    class Other
      def double_thing()
        thing + thing
      end
    end

    The approach you take will depend on balancing other factors in your code.

    SurveysController#nested_values? calls 'value_to_check.class' 3 times
    Open

          result << true if value_to_check.class == String && value_to_check.present?
    
          if value_to_check.class == Array
            value_to_check.each do |value|
              nested_values?(value, result)
    Severity: Minor
    Found in app/controllers/surveys_controller.rb by reek

    Duplication occurs when two fragments of code look nearly identical, or when two fragments of code have nearly identical effects at some conceptual level.

    Reek implements a check for Duplicate Method Call.

    Example

    Here's a very much simplified and contrived example. The following method will report a warning:

    def double_thing()
      @other.thing + @other.thing
    end

    One quick approach to silence Reek would be to refactor the code thus:

    def double_thing()
      thing = @other.thing
      thing + thing
    end

    A slightly different approach would be to replace all calls of double_thing by calls to @other.double_thing:

    class Other
      def double_thing()
        thing + thing
      end
    end

    The approach you take will depend on balancing other factors in your code.

    SurveysController#edit_survey_record calls 'survey.question_title' 2 times
    Open

            question_title_de: survey.question_title["de"],
            question_title_pl: survey.question_title["pl"],
    Severity: Minor
    Found in app/controllers/surveys_controller.rb by reek

    Duplication occurs when two fragments of code look nearly identical, or when two fragments of code have nearly identical effects at some conceptual level.

    Reek implements a check for Duplicate Method Call.

    Example

    Here's a very much simplified and contrived example. The following method will report a warning:

    def double_thing()
      @other.thing + @other.thing
    end

    One quick approach to silence Reek would be to refactor the code thus:

    def double_thing()
      thing = @other.thing
      thing + thing
    end

    A slightly different approach would be to replace all calls of double_thing by calls to @other.double_thing:

    class Other
      def double_thing()
        thing + thing
      end
    end

    The approach you take will depend on balancing other factors in your code.

    SurveysController#edit_survey_record calls 'response_option.title' 2 times
    Open

                title_de: response_option.title["de"],
                title_pl: response_option.title["pl"],
    Severity: Minor
    Found in app/controllers/surveys_controller.rb by reek

    Duplication occurs when two fragments of code look nearly identical, or when two fragments of code have nearly identical effects at some conceptual level.

    Reek implements a check for Duplicate Method Call.

    Example

    Here's a very much simplified and contrived example. The following method will report a warning:

    def double_thing()
      @other.thing + @other.thing
    end

    One quick approach to silence Reek would be to refactor the code thus:

    def double_thing()
      thing = @other.thing
      thing + thing
    end

    A slightly different approach would be to replace all calls of double_thing by calls to @other.double_thing:

    class Other
      def double_thing()
        thing + thing
      end
    end

    The approach you take will depend on balancing other factors in your code.

    SurveysController assumes too much for instance variable '@survey_params'
    Open

    class SurveysController < ApplicationController
    Severity: Minor
    Found in app/controllers/surveys_controller.rb by reek

    Classes should not assume that instance variables are set or present outside of the current class definition.

    Good:

    class Foo
      def initialize
        @bar = :foo
      end
    
      def foo?
        @bar == :foo
      end
    end

    Good as well:

    class Foo
      def foo?
        bar == :foo
      end
    
      def bar
        @bar ||= :foo
      end
    end

    Bad:

    class Foo
      def go_foo!
        @bar = :foo
      end
    
      def foo?
        @bar == :foo
      end
    end

    Example

    Running Reek on:

    class Dummy
      def test
        @ivar
      end
    end

    would report:

    [1]:InstanceVariableAssumption: Dummy assumes too much for instance variable @ivar

    Note that this example would trigger this smell warning as well:

    class Parent
      def initialize(omg)
        @omg = omg
      end
    end
    
    class Child < Parent
      def foo
        @omg
      end
    end

    The way to address the smell warning is that you should create an attr_reader to use @omg in the subclass and not access @omg directly like this:

    class Parent
      attr_reader :omg
    
      def initialize(omg)
        @omg = omg
      end
    end
    
    class Child < Parent
      def foo
        omg
      end
    end

    Directly accessing instance variables is considered a smell because it breaks encapsulation and makes it harder to reason about code.

    If you don't want to expose those methods as public API just make them private like this:

    class Parent
      def initialize(omg)
        @omg = omg
      end
    
      private
      attr_reader :omg
    end
    
    class Child < Parent
      def foo
        omg
      end
    end

    Current Support in Reek

    An instance variable must:

    • be set in the constructor
    • or be accessed through a method with lazy initialization / memoization.

    If not, Instance Variable Assumption will be reported.

    Method nested_values? has a Cognitive Complexity of 6 (exceeds 5 allowed). Consider refactoring.
    Open

        def nested_values?(value_to_check, result = [])
          result << true if value_to_check.class == String && value_to_check.present?
    
          if value_to_check.class == Array
            value_to_check.each do |value|
    Severity: Minor
    Found in app/controllers/surveys_controller.rb - About 25 mins to fix

    Cognitive Complexity

    Cognitive Complexity is a measure of how difficult a unit of code is to intuitively understand. Unlike Cyclomatic Complexity, which determines how difficult your code will be to test, Cognitive Complexity tells you how difficult your code will be to read and comprehend.

    A method's cognitive complexity is based on a few simple rules:

    • Code is not considered more complex when it uses shorthand that the language provides for collapsing multiple statements into one
    • Code is considered more complex for each "break in the linear flow of the code"
    • Code is considered more complex when "flow breaking structures are nested"

    Further reading

    SurveysController#new_survey_record doesn't depend on instance state (maybe move it to another class?)
    Open

        def new_survey_record
    Severity: Minor
    Found in app/controllers/surveys_controller.rb by reek

    A Utility Function is any instance method that has no dependency on the state of the instance.

    SurveysController#update has the variable name 'e'
    Open

        rescue Graphlient::Errors::GraphQLError => e
    Severity: Minor
    Found in app/controllers/surveys_controller.rb by reek

    An Uncommunicative Variable Name is a variable name that doesn't communicate its intent well enough.

    Poor names make it hard for the reader to build a mental picture of what's going on in the code. They can also be mis-interpreted; and they hurt the flow of reading, because the reader must slow down to interpret the names.

    SurveysController#create has the variable name 'e'
    Open

        rescue Graphlient::Errors::GraphQLError => e
    Severity: Minor
    Found in app/controllers/surveys_controller.rb by reek

    An Uncommunicative Variable Name is a variable name that doesn't communicate its intent well enough.

    Poor names make it hard for the reader to build a mental picture of what's going on in the code. They can also be mis-interpreted; and they hurt the flow of reading, because the reader must slow down to interpret the names.

    Similar blocks of code found in 7 locations. Consider refactoring.
    Open

      def create
        query = create_params
        begin
          results = @smart_village.query query
        rescue Graphlient::Errors::GraphQLError => e
    Severity: Major
    Found in app/controllers/surveys_controller.rb and 6 other locations - About 50 mins to fix
    app/controllers/constructions_controller.rb on lines 90..102
    app/controllers/events_controller.rb on lines 208..220
    app/controllers/jobs_controller.rb on lines 117..129
    app/controllers/offers_controller.rb on lines 102..114
    app/controllers/point_of_interests_controller.rb on lines 172..184
    app/controllers/tours_controller.rb on lines 149..161

    Duplicated Code

    Duplicated code can lead to software that is hard to understand and difficult to change. The Don't Repeat Yourself (DRY) principle states:

    Every piece of knowledge must have a single, unambiguous, authoritative representation within a system.

    When you violate DRY, bugs and maintenance problems are sure to follow. Duplicated code has a tendency to both continue to replicate and also to diverge (leaving bugs as two similar implementations differ in subtle ways).

    Tuning

    This issue has a mass of 42.

    We set useful threshold defaults for the languages we support but you may want to adjust these settings based on your project guidelines.

    The threshold configuration represents the minimum mass a code block must have to be analyzed for duplication. The lower the threshold, the more fine-grained the comparison.

    If the engine is too easily reporting duplication, try raising the threshold. If you suspect that the engine isn't catching enough duplication, try lowering the threshold. The best setting tends to differ from language to language.

    See codeclimate-duplication's documentation for more information about tuning the mass threshold in your .codeclimate.yml.

    Refactorings

    Further Reading

    Identical blocks of code found in 2 locations. Consider refactoring.
    Open

        def nested_values?(value_to_check, result = [])
          result << true if value_to_check.class == String && value_to_check.present?
    
          if value_to_check.class == Array
            value_to_check.each do |value|
    Severity: Minor
    Found in app/controllers/surveys_controller.rb and 1 other location - About 45 mins to fix
    app/controllers/application_controller.rb on lines 67..80

    Duplicated Code

    Duplicated code can lead to software that is hard to understand and difficult to change. The Don't Repeat Yourself (DRY) principle states:

    Every piece of knowledge must have a single, unambiguous, authoritative representation within a system.

    When you violate DRY, bugs and maintenance problems are sure to follow. Duplicated code has a tendency to both continue to replicate and also to diverge (leaving bugs as two similar implementations differ in subtle ways).

    Tuning

    This issue has a mass of 41.

    We set useful threshold defaults for the languages we support but you may want to adjust these settings based on your project guidelines.

    The threshold configuration represents the minimum mass a code block must have to be analyzed for duplication. The lower the threshold, the more fine-grained the comparison.

    If the engine is too easily reporting duplication, try raising the threshold. If you suspect that the engine isn't catching enough duplication, try lowering the threshold. The best setting tends to differ from language to language.

    See codeclimate-duplication's documentation for more information about tuning the mass threshold in your .codeclimate.yml.

    Refactorings

    Further Reading

    Similar blocks of code found in 11 locations. Consider refactoring.
    Open

          if @survey_params["response_options"].present?
            response_options = []
            @survey_params["response_options"].each do |_key, response_option|
              next if response_option.blank?
              next unless nested_values?(response_option.to_h).include?(true)
    Severity: Major
    Found in app/controllers/surveys_controller.rb and 10 other locations - About 30 mins to fix
    app/controllers/constructions_controller.rb on lines 231..239
    app/controllers/deadlines_controller.rb on lines 238..246
    app/controllers/events_controller.rb on lines 320..328
    app/controllers/events_controller.rb on lines 332..340
    app/controllers/events_controller.rb on lines 359..367
    app/controllers/events_controller.rb on lines 386..394
    app/controllers/jobs_controller.rb on lines 198..206
    app/controllers/jobs_controller.rb on lines 251..259
    app/controllers/news_items_controller.rb on lines 219..227
    app/controllers/offers_controller.rb on lines 223..231

    Duplicated Code

    Duplicated code can lead to software that is hard to understand and difficult to change. The Don't Repeat Yourself (DRY) principle states:

    Every piece of knowledge must have a single, unambiguous, authoritative representation within a system.

    When you violate DRY, bugs and maintenance problems are sure to follow. Duplicated code has a tendency to both continue to replicate and also to diverge (leaving bugs as two similar implementations differ in subtle ways).

    Tuning

    This issue has a mass of 33.

    We set useful threshold defaults for the languages we support but you may want to adjust these settings based on your project guidelines.

    The threshold configuration represents the minimum mass a code block must have to be analyzed for duplication. The lower the threshold, the more fine-grained the comparison.

    If the engine is too easily reporting duplication, try raising the threshold. If you suspect that the engine isn't catching enough duplication, try lowering the threshold. The best setting tends to differ from language to language.

    See codeclimate-duplication's documentation for more information about tuning the mass threshold in your .codeclimate.yml.

    Refactorings

    Further Reading

    Similar blocks of code found in 6 locations. Consider refactoring.
    Open

      def destroy
        results = @smart_village.query <<~GRAPHQL
          mutation {
            destroyRecord(
              id: #{params["id"]},
    Severity: Major
    Found in app/controllers/surveys_controller.rb and 5 other locations - About 30 mins to fix
    app/controllers/deadlines_controller.rb on lines 135..154
    app/controllers/defect_reports_controller.rb on lines 55..74
    app/controllers/noticeboards_controller.rb on lines 49..68
    app/controllers/static_contents_controller.rb on lines 74..93
    app/controllers/tours_controller.rb on lines 179..198

    Duplicated Code

    Duplicated code can lead to software that is hard to understand and difficult to change. The Don't Repeat Yourself (DRY) principle states:

    Every piece of knowledge must have a single, unambiguous, authoritative representation within a system.

    When you violate DRY, bugs and maintenance problems are sure to follow. Duplicated code has a tendency to both continue to replicate and also to diverge (leaving bugs as two similar implementations differ in subtle ways).

    Tuning

    This issue has a mass of 32.

    We set useful threshold defaults for the languages we support but you may want to adjust these settings based on your project guidelines.

    The threshold configuration represents the minimum mass a code block must have to be analyzed for duplication. The lower the threshold, the more fine-grained the comparison.

    If the engine is too easily reporting duplication, try raising the threshold. If you suspect that the engine isn't catching enough duplication, try lowering the threshold. The best setting tends to differ from language to language.

    See codeclimate-duplication's documentation for more information about tuning the mass threshold in your .codeclimate.yml.

    Refactorings

    Further Reading

    Similar blocks of code found in 2 locations. Consider refactoring.
    Open

        begin
          @smart_village.query query
        rescue Graphlient::Errors::GraphQLError => e
          flash[:error] = e.errors.messages["data"].to_s
          @survey = edit_survey_record
    Severity: Minor
    Found in app/controllers/surveys_controller.rb and 1 other location - About 15 mins to fix
    app/controllers/static_contents_controller.rb on lines 62..69

    Duplicated Code

    Duplicated code can lead to software that is hard to understand and difficult to change. The Don't Repeat Yourself (DRY) principle states:

    Every piece of knowledge must have a single, unambiguous, authoritative representation within a system.

    When you violate DRY, bugs and maintenance problems are sure to follow. Duplicated code has a tendency to both continue to replicate and also to diverge (leaving bugs as two similar implementations differ in subtle ways).

    Tuning

    This issue has a mass of 25.

    We set useful threshold defaults for the languages we support but you may want to adjust these settings based on your project guidelines.

    The threshold configuration represents the minimum mass a code block must have to be analyzed for duplication. The lower the threshold, the more fine-grained the comparison.

    If the engine is too easily reporting duplication, try raising the threshold. If you suspect that the engine isn't catching enough duplication, try lowering the threshold. The best setting tends to differ from language to language.

    See codeclimate-duplication's documentation for more information about tuning the mass threshold in your .codeclimate.yml.

    Refactorings

    Further Reading

    Line is too long. [121/100]
    Open

          @survey_params["question_allow_multiple_responses"] = @survey_params["question_allow_multiple_responses"] == "true"

    Missing top-level class documentation comment.
    Open

    class SurveysController < ApplicationController

    This cop checks for missing top-level documentation of classes and modules. Classes with no body are exempt from the check and so are namespace modules - modules that have nothing in their bodies except classes, other modules, or constant definitions.

    The documentation requirement is annulled if the class or module has a "#:nodoc:" comment next to it. Likewise, "#:nodoc: all" does the same for all its children.

    Example:

    # bad
    class Person
      # ...
    end
    
    # good
    # Description/Explanation of Person class
    class Person
      # ...
    end

    Use a guard clause instead of wrapping the code inside a conditional expression.
    Open

          if @survey_params["response_options"].present?

    Use a guard clause instead of wrapping the code inside a conditional expression

    Example:

    # bad
    def test
      if something
        work
      end
    end
    
    # good
    def test
      return unless something
      work
    end
    
    # also good
    def test
      work if something
    end
    
    # bad
    if something
      raise 'exception'
    else
      ok
    end
    
    # good
    raise 'exception' if something
    ok

    There are no issues that match your filters.

    Category
    Status