Class: ExposeAssociation::AssociationExposer

Inherits:
Object
  • Object
show all
Defined in:
lib/expose_association/base.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(klass, association_name, options = {}) ⇒ AssociationExposer

Returns a new instance of AssociationExposer.



27
28
29
30
31
32
33
# File 'lib/expose_association/base.rb', line 27

def initialize klass, association_name, options = {}
  @klass = klass
  options[:class] ||= association_name.to_s.camelize.constantize
  @association_class = options[:class]
  @association_name = association_name
  @options = options
end

Instance Attribute Details

#association_classObject (readonly)

Returns the value of attribute association_class.



25
26
27
# File 'lib/expose_association/base.rb', line 25

def association_class
  @association_class
end

#association_nameObject (readonly)

Returns the value of attribute association_name.



25
26
27
# File 'lib/expose_association/base.rb', line 25

def association_name
  @association_name
end

Instance Method Details

#association_attributesObject



70
71
72
# File 'lib/expose_association/base.rb', line 70

def association_attributes
  "#{association_name}_attributes"
end

#association_setup_methodObject



74
75
76
# File 'lib/expose_association/base.rb', line 74

def association_setup_method
  "#{setup_method_prefix}_#{@association_name}"
end

#attr_name_for(name, prefix) ⇒ Object



50
51
52
53
54
55
56
57
58
# File 'lib/expose_association/base.rb', line 50

def attr_name_for(name, prefix)
  case prefix
  when FalseClass then name.to_s
  when String, Symbol then 
    "#{prefix.to_s}_#{name}"
  else
    "#{association_name}_#{name}"
  end
end

#expose(*attributes) ⇒ Object



35
36
37
38
39
40
# File 'lib/expose_association/base.rb', line 35

def expose *attributes
  options = attributes.last.is_a?(Hash) ? attributes.pop : {}
  attributes.each do |attribute|
    expose_attribute attribute, options
  end
end

#expose_attribute(name, options = {}) ⇒ Object



42
43
44
45
46
47
48
# File 'lib/expose_association/base.rb', line 42

def expose_attribute name, options = {}
  @klass.delegate name, "#{name}=",
    to: association_setup_method,
    prefix: prefix_for(options[:prefix])

  @klass.attr_accessible attr_name_for(name, options[:prefix])
end

#prefix_for(prefix_option) ⇒ Object



60
61
62
63
64
65
66
67
68
# File 'lib/expose_association/base.rb', line 60

def prefix_for(prefix_option)
  case prefix_option
  when TrueClass, NilClass then association_name.to_s
  when FalseClass then false
  when String, Symbol then prefix_option.to_s
  else # nil
    raise "Wrong value for prefix: #{prefix_option}"
  end
end

#setup_method_prefixObject



78
79
80
# File 'lib/expose_association/base.rb', line 78

def setup_method_prefix
  @options.fetch(:setup_method_prefix, "setup")
end