Robby Williams Robby Williams - 16 days ago 5
Ruby Question

Setting instance variable value in model using controller with Ruby

The check in the controller evaluates properly for

if o.my_method('a')
, although when this happens
@var
stays nil in the model. Where am I going wrong, or is there a better way to do this?

Controller:

def action
o = Object.new
if o.my_method('a')
...
end
end


Model:

class Object
def my_method(args)
['a', 'b', 'c'].any? do |i|
@var = true if args.include?(i)
end
end

def my_method2
if @var == true
do stuff
end
end
end

Answer

Here's a cleaned up version of your code that's actually more Ruby-like in nature:

class MyModel
  attr_accessor :example

  VALID_VALUES = %w[ a b c ]

  def demo_method(value)
    @example = true if VALID_VALUES.include?(value)
  end
end

model = MyModel.new

model.demo_method('x')

model.example
# => nil

model.demo_method('a')

model.example
# => true

The problem you had in your original code is you're setting the value inside an any? block which also does a test for inclusion. This nesting isn't required.

You also don't need to test x == true since x will suffice.