Michael
Michael

Reputation: 37

rails class instead of switch

I have been looking for over an hour on Internet and I can't find anything about this.

I am creating filters for data of a website and currently these are handled by a case statement

  class MyClass
    attr_accessor :attribute
    def self.function(value)
      query = case value
        when "open" then "Open"
        ...
      end
      where(:attribute => query)
    end
 end

Because of various reasons (i.e. dynamic instead of hard coding the filters) I want to create a model out of this with a getter and setter, but I can't get this to work

My new function:

def self.function(value)
  Attribute.name = value
  where(:attribute => Attribute.name)
end

My new model:

class Attribute
  attr_accessor :name
end

And the test:

it "should set the attribute to 'hello'" do
    MyClass.function("hello")
    Attribute.name.should eql "hello"
end

gives an error:

Failure/Error: Myclass.function("hallo")
 NoMethodError:
   undefined method `name=' for Attribute:Class

Any help would be appreciated

Upvotes: 0

Views: 73

Answers (1)

Adrien Coquio
Adrien Coquio

Reputation: 4930

This is because the attr_accessor is defining instance method (ie: method that works on an instance of Attribute) and you try to use it as class method (ie: Attribute.name).

You may rewrite your function this way :

def self.function(value)
  attribute = Attribute.new
  attribute.name = value
  where(:attribute => attribute.name)
end

Upvotes: 1

Related Questions