Last active
September 20, 2021 15:30
-
-
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)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
update_from_hash
for non AR code.