0

I wrote a lib/animal.rb with several lists of params, and I want to reference that list in my controller and add it my params list. I did this because I use this list in several locations and didn't want to litter my code with a bunch of references to the library.

Controller

ANIMAL_TYPE_INPUT_PARAMS = *Animals::ANIMAL_TYPE_PARAMS.freeze

....

def familar_params
  params.permit(ANIMAL_TYPE_INPUT_PARAMS, OTHER_PARAM_LIST....)
end

Lib/animal.rb

module Animal

  # param lists
  ANIMAL_TYPE_PARAMS = [
    :animal_has_fur, :animal_id, :animal_weight
  ].freeze
end

Functionally it works just fine, but I am seeing a weird rubocop error. I would prefer to not disable MutableConstant for this section (disabling rubocop is usually a band aid that you pay for at some point).

Rubocop error

app/controllers/api/v1/example_controller.rb:55:24: C: Freeze mutable objects assigned to constants.
  ANIMAL_TYPE_INPUT_PARAMS = *Animals::ANIMAL_TYPE_PARAMS.freeze
                             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

I looked into this question: Ruby rubocop: how to freeze an array constant generated with splat But mine are already arrays, so I feel like it doesn't apply to me / shouldn't have to call to_a.

Community
  • 1
  • 1
alex_milhouse
  • 891
  • 1
  • 13
  • 31
  • You don't need to freeze a constant, since it should... well, be constant. Remove the `.freeze` from `Animals::ANIMAL_TYPE_PARAMS` and keep it on the array in `lib/animal.rb` and you'll be fine. – binarymason Dec 16 '16 at 22:58
  • @binarymason My apologies. I had a huge typo! I am splatting the array. to the new params list – alex_milhouse Dec 16 '16 at 23:32
  • Why cant you ANIMAL_TYPE_INPUT_PARAMS = Animals::ANIMAL_TYPE_PARAMS – sonnyhe2002 Dec 17 '16 at 02:07
  • I get the same error of: Freeze mutable objects assigned to constants. If I do not splat it. And I need to splat it so that it can be in the params list. – alex_milhouse Dec 17 '16 at 03:08
  • Whoops. Thought I had fixed this in a previous PR. Looks like there might be more edge cases. I will have a look at this once I have some free time. :-) – Drenmi Dec 17 '16 at 15:48
  • @alex_milhouse: Which version of RuboCop are you using? I can not reproduce this in `0.46.0` using the code you provided. – Drenmi Dec 19 '16 at 10:07
  • @Drenmi I am on version .0.42.0 . I will try upgrading and report back – alex_milhouse Dec 19 '16 at 18:46

1 Answers1

0

As @drenmi suggested, it was an older version of rubocop giving me this error. Once I upgraded to 0.46.0 the error was no longer.

alex_milhouse
  • 891
  • 1
  • 13
  • 31