Reputation: 7101
I have a model with 30 attributes. but those attributes can be grouped in 2 groups.
For example I have:
string:title
string:text
...
and
string:title_old
string:text_old
...
I want to be able: When I check title
attribute at the same time to check the title_old
attribute. Can I perform that with a loop if I make an array of the 15 first strings or I should write hard coded if statements
Final goal:
[
{
:name => :title,
:y => 1 (constant),
:color=> red, (if title_old == "something" color = red else color = green)
},
{
:name=> :text,
:y => 1 (constant)
:color => red (if text_old == "something" color = red else color = green)
},
.... (all other 13 attributes)
]
Upvotes: 1
Views: 121
Reputation: 83680
your model:
class MyModel < AR::Base
def attributize
attrs = self.attributes.except(:created_at, :updated_at).reject{ |attr, val| attr =~ /.*_old/ && !val }
attrs.inject([]) do |arr, (attr, val)|
arr << { :name => attr, :y => 1, :color => (self.send("#{attr}_old") == "something" ? "red" : "green") }
end
end
end
usage:
my_object = MyModel.last
my_object.attributize
Upvotes: 1
Reputation: 2797
use state_machine, that way your logic will be in one place with a clear dsl. https://github.com/pluginaweek/state_machine
Upvotes: 0
Reputation: 5570
Very simple example:
class MyModel
def identify_color
if send("#{name}_old".to_sym) == "something"
'red'
else
'green'
end
end
end
MyModel.all.collect do |instance|
attrs = instance.attributes
attrs.merge!('color' => identify_color)
attrs
end
Add some rescue at will, but it can be done in different ways.
Upvotes: 1
Reputation: 64363
Try this:
[
:title,
..,
..
:description
].map do |attr|
{
:name => attr,
:y => 1 (constant),
:color=> (read_attribute("#{attr}_old") == "something") ? "red" : "green"
}
end
PS: Naming an attribute text
is a bad idea.
Upvotes: 0