I am using ActiveModel because I am hooking up to a third party API rather than a db. I have written my own initialiser so that I can pass in a hash and this be converted to attributes on the model – to support some of the forms in the application.
attr_accessor :Id, :FirstName, :LastName,...
def initialize(attributes = {})
attributes.each do |name, value|
send("#{name}=", value)
end
end
The problem is that I want to use the same model to handle the data retrieval from the API, but this has a load of other data I don’t really care about. As such I want to check as I iterate through the hash returned from the API and check if the attribute exists on my model and if not then just ignore it. This should allow me to have a consistent model for both the form posts and the data returned from the API. Something like:
def initialize(attributes = {})
attributes.each do |name, value|
if self.has_attribute?(name)
send("#{name}=", value)
end
end
end
I have looked through the ActiveModel API docs but there doesn’t seem to be an equivalent. This is making me feel as though I should be doing this differently.
Is this the right (Rails) way to do this? How do I ensure I have consistent model attributes when the data is coming from different sources?
Based on the code example above, you don’t need to use an ActiveModel method similar to
has_attribute?at all–you can simply fall back to plain ol’ Ruby:This will only assign the attribute if it has been initiated with
attr_accessor.