Skip to content

Instantly share code, notes, and snippets.

@merbjedi
Created December 9, 2008 00:45
Show Gist options
  • Save merbjedi/33704 to your computer and use it in GitHub Desktop.
Save merbjedi/33704 to your computer and use it in GitHub Desktop.
Easier Bulk Attribute Setting/Updating for Datamapper
# Mass assign of attributes
#
# ==== Parameters
# value_hash <Hash[<Symbol>]>::
#
# --
# @api public
def attributes=(values_hash)
values_hash.each do |name, value|
name = name.to_s.sub(/\?\z/, '')
if self.class.public_method_defined?(setter = "#{name}=")
send(setter, value)
else
raise ArgumentError, "The property '#{name}' is not a public property."
end
end
end
# Updates attributes and saves model
#
# ==== Parameters
# attributes<Hash> Attributes to be updated
# keys<Symbol, String, Array> keys of Hash to update (others won't be updated)
#
# ==== Returns
# <TrueClass, FalseClass> if model got saved or not
#
#-
# @api public
def update_attributes(hash, *update_only)
set_attributes(hash, *update_only)
save
end
# Sets attributes on a model
#
# ==== Parameters
# attributes<Hash> Attributes to be updated
# keys<Symbol, String, Array> keys of Hash to update (others won't be set)
#
# ==== Returns
# <Hash> of key/values updated
#
#-
# @api public
def set_attributes(values_hash, *update_only)
unless values_hash.is_a?(Hash)
raise ArgumentError, "Expecting the first parameter of " +
"set_attributes to be a hash; got #{values_hash.inspect}"
end
unless update_only.empty?
truncated_hash = {}
update_only.each { |attr| truncated_hash[attr] = values_hash[attr] }
values_hash = truncated_hash
end
self.attributes = values_hash
return values_hash
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment