class Mushy::Masher
Attributes
mash_methods[RW]
Public Class Methods
new()
click to toggle source
# File lib/mushy/masher.rb, line 7 def initialize self.mash_methods = { String => ->(x, d) do x.match('{{\s?(\w*)\s?}}') do |m| if (m.captures.count == 1) match_on_key = d.keys.select { |x| x.to_s == m.captures[0].to_s }.first if match_on_key value = dig match_on_key.to_s, d return value unless value.is_a?(String) || value.is_a?(Numeric) end end end Liquid::Template.parse(x).render SymbolizedHash.new(d) end, Hash => ->(x, d) do h = SymbolizedHash.new(x) h.each { |k, v| h[k] = mash v, d } h end, Array => ->(x, d) { x.map { |x| mash x, d } } } end
Public Instance Methods
dig(key, data)
click to toggle source
# File lib/mushy/masher.rb, line 42 def dig key, data return nil unless key segments = key.split '.' segments.each do |segment| if segment.include?('[') && segment.include?(']') the_splits = segment.split('[') segment = the_splits[0] index = the_splits[1].sub(']', '') data = data.is_a?(Hash) ? (data[segment] || data[segment.to_sym]) : (data ? data.send(segment.to_sym) : nil) data = data[index.to_i] else data = data.is_a?(Hash) ? (data[segment] || data[segment.to_sym]) : (data ? data.send(segment.to_sym) : nil) end end data end
mash(value, data)
click to toggle source
# File lib/mushy/masher.rb, line 31 def mash value, data method_for(value).call value, data end
method_for(value)
click to toggle source
# File lib/mushy/masher.rb, line 35 def method_for value mash_methods .select { |k, _| value.is_a? k } .map { |_, v| v } .first || ->(x, _) { x } end