Module: Duplo

Defined in:
lib/duplo.rb,
lib/duplo/version.rb

Constant Summary collapse

TOYS =
{
  "a" => Array,
  "s" => Set,
  "h" => Hash
}
BRICK =
/[#{TOYS.keys.join}]\d*/
VERSION =
"0.1.2"

Class Attribute Summary collapse

Class Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method_name, *arguments, &block) ⇒ Object (private)



78
79
80
81
82
83
84
85
# File 'lib/duplo.rb', line 78

def method_missing(method_name, *arguments, &block)
  toy = method_name.to_s
  if Duplo.can_build? toy
    Duplo.build toy, *arguments, &block
  else
    super
  end
end

Class Attribute Details

.default_sizeObject



18
19
20
# File 'lib/duplo.rb', line 18

def default_size
  @default_size || 5
end

Class Method Details

.add(toy, part) ⇒ Object



22
23
24
25
26
27
28
29
# File 'lib/duplo.rb', line 22

def add(toy, part)
  case toy
  when Array, Set
    toy << part
  when Hash
    toy.store(toy.size, part)
  end
end

.build(part, path = [], &block) ⇒ Object



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/duplo.rb', line 35

def build(part, path = [], &block)
  raise %(Don't know how to build "#{part}", sorry) unless can_build? part

  part = part.dup
  brick = part.slice! BRICK
  type, size = crack brick
  toy = type.new

  if part.empty?
    block ||= proc { |path| path.is_a?(Array) ? path.last : path }
    size.times { |i| add toy, block.call(path.empty? ? i : path + [i]) }
  else
    size.times { |i| add toy, build(part, path + [i], &block) }
  end

  toy
end

.can_build?(toy) ⇒ Boolean

Returns:

  • (Boolean)


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

def can_build?(toy)
  !!(toy.strip =~ /\A#{BRICK}+\z/)
end

.crack(brick) ⇒ Object



57
58
59
60
61
# File 'lib/duplo.rb', line 57

def crack(brick)
  type, size = brick.split("", 2)
  size = size.empty? ? default_size : size.to_i
  [TOYS[type], size]
end

.method_missing(method_name, *arguments, &block) ⇒ Object



78
79
80
81
82
83
84
85
# File 'lib/duplo.rb', line 78

def method_missing(method_name, *arguments, &block)
  toy = method_name.to_s
  if Duplo.can_build? toy
    Duplo.build toy, *arguments, &block
  else
    super
  end
end

.respond_to_missing?(method_name) ⇒ Boolean

Returns:

  • (Boolean)


73
74
75
76
# File 'lib/duplo.rb', line 73

def respond_to_missing?(method_name, *)
  toy = method_name.to_s
  Duplo.can_build?(toy) || super
end

.smash(toy) ⇒ Object



53
54
55
# File 'lib/duplo.rb', line 53

def smash(toy)
  toy.scan(BRICK).map { |brick| crack brick }
end

.spell(toy) ⇒ Object



63
64
65
66
67
68
# File 'lib/duplo.rb', line 63

def spell(toy)
  smash(toy).map.with_index do |(type, size), idx|
    plural = idx == 0 ? "" : type == Hash ? "es" : "s"
    size.zero? ? "empty #{type}#{plural}" : "#{size}-element #{type}#{plural}"
  end.join(" containing ")
end