Skip to content

Instantly share code, notes, and snippets.

@nilsandrey
Last active September 20, 2021 15:30
Show Gist options
  • Save nilsandrey/d418c7b4466b46ec16473073cfd4d4da to your computer and use it in GitHub Desktop.
Save nilsandrey/d418c7b4466b46ec16473073cfd4d4da to your computer and use it in GitHub Desktop.
Ruby convert Object to Hash (and read hash to attributes in case of AR objects)
module ObjectExtension
# For any object...
def to_hash
hash = {}
instance_variables.each {|var| hash[var.to_s.delete("@")] = instance_variable_get(var) }
hash
end
##
# Update all attributes with values from a hash. Only update existing attributes.
# NOTICE: The attributes expected must be defined in attr_accesor.
# A safer variant is to define attributes in an array and substitute methods.include?
# with attributes.include?.
#
# ```
# attributes = %i{attr1 attr2 attr3} # This automatically exists in ActiveRecord
# attr_accessor *attributes
# ```
#
# @param [Hash] attr_values
def update_from_hash(attr_values)
filtered_attributes = attr_values.filter { |k, v| methods.include?(k.to_sym)}
assign_attributes(filtered_attributes)
end
end
module ActiveRecordExtension
# For ActiveRecord objects...
def to_hash
hash = {}
self.attributes.each { |k,v| hash[k] = v }
hash
end
##
# Update all attributes with values from a hash. Only update existing attributes.
# @param [Hash] attr_values
def update_from_hash(attr_values)
filtered_attributes = attr_values.filter { |k, v| attributes.key?(k)}
assign_attributes(filtered_attributes)
end
end
@nilsandrey
Copy link
Author

nilsandrey commented Jul 28, 2021

@nilsandrey
Copy link
Author

nilsandrey commented Sep 20, 2021

  • Included update_from_hash for non AR code.
  • Added tip on comments based on an answer of a non directly related question in SO provided by @davetapley.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment