Class: Mushy::Masher

Inherits:
Object
  • Object
show all
Defined in:
lib/mushy/masher.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeMasher

Returns a new instance of Masher.



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# 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

Instance Attribute Details

#mash_methodsObject

Returns the value of attribute mash_methods.



5
6
7
# File 'lib/mushy/masher.rb', line 5

def mash_methods
  @mash_methods
end

Instance Method Details

#dig(key, data) ⇒ Object



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# 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) ⇒ Object



31
32
33
# File 'lib/mushy/masher.rb', line 31

def mash value, data
  method_for(value).call value, data
end

#method_for(value) ⇒ Object



35
36
37
38
39
40
# 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