Class: XDry::Generators::StoringConstructor

Inherits:
Generator
  • Object
show all
Defined in:
lib/xdry/generators/storing_constructor.rb

Instance Attribute Summary

Attributes inherited from Generator

#patcher

Instance Method Summary collapse

Methods inherited from Generator

id, inherited, #initialize, #process_attribute, #verbose?

Constructor Details

This class inherits a constructor from XDry::Generators::Generator

Instance Method Details

#process_class(oclass) ⇒ Object



8
9
10
11
12
13
14
15
# File 'lib/xdry/generators/storing_constructor.rb', line 8

def process_class oclass
  oclass.methods.each do |omethod|
    case omethod.selector
    when /^initWith/
      process_method oclass, omethod
    end
  end
end

#process_method(oclass, omethod) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/xdry/generators/storing_constructor.rb', line 17

def process_method oclass, omethod
  components = omethod.header_or_impl.selector_def.components
  mapping = {}
  components.each do |comp|
    kw = comp.keyword_without_colon
    oattr = oclass.find_attribute(kw)
    if oattr.nil? and comp == components.first
      stripped_kw = kw.gsub(/^initWith/, '')
      [stripped_kw.downcase, stripped_kw[0..0].downcase + stripped_kw[1..-1]].each do |alt_kw|
        oattr = oclass.find_attribute(alt_kw)
        break unless oattr.nil?
      end
    end
    mapping[kw] = oattr unless oattr.nil?
  end

  unless mapping.empty?
    new_selector_def = CompoundSelectorDef.new(components.collect do |comp|
      if oattr = mapping[kw = comp.keyword_without_colon]
        arg_name = comp.arg_name
        arg_name = oattr.name if arg_name.empty?
        SelectorComponent.new(comp.keyword, arg_name, comp.type || oattr.type)
      else
        comp
      end
    end)
    method_header = NMethodHeader.new(new_selector_def, omethod.ret_type)

    init_out = Emitter.new

    new_selector_def.components.each do |comp|
      if oattr = mapping[kw = comp.keyword_without_colon]
        field_name = oattr.field_name
        arg_name = comp.arg_name
        type = comp.type
        retain_policy = Boxing.retain_policy_of(type)

        retained = retain_policy.retain(arg_name)
        init_out << "#{field_name} = #{retained};"
      end
    end

    # out << "#{method_header};"
    # out.block "#{method_header}" do
    #   out.if "self = [super init]" do
    #     out << init_out
    #   end
    #   out << "return self;"
    # end
  end
end