Ruby access nested attributes with symbol -
i'm trying write method takes an object, a symbol (or else, here's question) , "upcases" value @ key (for example).
simple case:
foo = { a: 'hi', b: 'there' } def upc_value(object, key) object[key].upcase! end upc_value(foo, :b) puts foo #=> { a: 'hi', b: 'there' }
but want method work nested attributes if foo
object more complex.
more complex case:
foo = { a: 'hi', b: [{ c: 'foo', d: 'bar' }, { c: 'bob', d: 'lisa' }] } def upc_value(object, key) object[key].upcase! end # able like: upc_value(foo, :b[:d]) puts foo #=> { a: 'hi', b: [{ c: 'foo', d: 'bar' }, { c: 'bob', d: 'lisa' }] }
i can't , i'm curious if "deep_symbol" exists...
real problem:
real thing i'm trying achieve here module removes host every field contains url before model saved.
it's included in every model needs , call fields_containing_url
method takes symbols of fields.
problem have nested attributes on 1 of models , need access them same method takes symbols...
thank you help!
here's start. it's recursive method changing data in place :
def deep_transform(object, key, &block) case object when array object.each |element| deep_transform(element, key, &block) end when hash object.each_value |value| deep_transform(value, key, &block) end if value = object[key] object[key] = yield(value) end end end foo = { a: 'hi', b: 'there' } deep_transform(foo, :b){ |str| str.upcase } p foo # {:a=>"hi", :b=>"there"} foo = { a: 'hi', b: [{ c: 'foo', d: 'bar' }, { c: 'bob', d: 'lisa' }] } deep_transform(foo, :d, &:upcase) # alternative way call method p foo # {:a=>"hi", :b=>[{:c=>"foo", :d=>"bar"}, {:c=>"bob", :d=>"lisa"}]}
note method mutate every value related :d
key. don't specify :b[:d]
in example.
Comments
Post a Comment