Class: AtCoderFriends::Generator::FragmentBase

Inherits:
Object
  • Object
show all
Defined in:
lib/at_coder_friends/generator/fragment.rb

Overview

base class for code fragment generator

Direct Known Subclasses

ConstFragment, InputFormatFragment

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(obj, templates) ⇒ FragmentBase

Returns a new instance of FragmentBase.



11
12
13
14
# File 'lib/at_coder_friends/generator/fragment.rb', line 11

def initialize(obj, templates)
  @obj = obj
  @templates = templates
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name, *args, &block) ⇒ Object

delegate method calls to obj



32
33
34
35
36
37
38
39
40
# File 'lib/at_coder_friends/generator/fragment.rb', line 32

def method_missing(name, *args, &block)
  if @obj.respond_to?(name)
    @obj.send(name, *args, &block)
  elsif templates.key?(name.to_s)
    render(name)
  else
    super
  end
end

Instance Attribute Details

#templatesObject (readonly)

Returns the value of attribute templates.



9
10
11
# File 'lib/at_coder_friends/generator/fragment.rb', line 9

def templates
  @templates
end

Instance Method Details

#render(*keys) ⇒ Object

Raises:



16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/at_coder_friends/generator/fragment.rb', line 16

def render(*keys)
  keys = keys.map(&:to_s)
  template = templates.dig(*keys) || (raise AppError, "fragment key #{keys} not found")

  return ERB.new(template, trim_mode: '-').result(binding) if template.is_a?(String)

  if template.is_a?(Hash)
    sub_key_props = template['__key'] || (raise AppError, "'__key' not found in fragment hash #{keys}")
    sub_keys = sub_key_props.map { |k| send(k) }
    return render(*keys, *sub_keys)
  end

  raise AppError, "can't render fragment #{keys}"
end

#respond_to_missing?(name, include_private = false) ⇒ Boolean

Returns:

  • (Boolean)


42
43
44
45
46
# File 'lib/at_coder_friends/generator/fragment.rb', line 42

def respond_to_missing?(name, include_private = false)
  @obj.respond_to?(name, include_private) ||
    templates.key?(name.to_s) ||
    super
end

#to_sObject



48
49
50
# File 'lib/at_coder_friends/generator/fragment.rb', line 48

def to_s
  @obj.to_s
end