Class: CanBe::Builder::CanBeDetail

Inherits:
Object
  • Object
show all
Defined in:
lib/can_be/builder/can_be_detail.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(klass, can_be_model, options) ⇒ CanBeDetail

Returns a new instance of CanBeDetail.



10
11
12
13
14
# File 'lib/can_be/builder/can_be_detail.rb', line 10

def initialize(klass, can_be_model, options)
  @klass = klass
  @can_be_model = can_be_model
  @options = parse_options(options)
end

Class Method Details

.build(klass, can_be_model, options = {}) ⇒ Object



6
7
8
# File 'lib/can_be/builder/can_be_detail.rb', line 6

def self.build(klass, can_be_model, options = {})
  new(klass, can_be_model, options).define_functionality
end

Instance Method Details

#define_associationObject



21
22
23
24
25
26
27
28
# File 'lib/can_be/builder/can_be_detail.rb', line 21

def define_association
  can_be_model = @can_be_model
  details_name = @options[:details_name]

  @klass.class_eval do
    has_one can_be_model, as: details_name.to_sym, dependent: :destroy
  end
end

#define_functionalityObject



16
17
18
19
# File 'lib/can_be/builder/can_be_detail.rb', line 16

def define_functionality
  define_association
  define_history
end

#define_historyObject



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
# File 'lib/can_be/builder/can_be_detail.rb', line 30

def define_history
  return unless keeps_history?

  history_model = @options[:history_model]
  details_name = @options[:details_name]
  can_be_model = @can_be_model

  @klass.instance_eval do
    define_method can_be_model do |*params|
      begin
        details = association(details_name).reader(false)
        return details
      rescue NoMethodError
        # this should be for the missing 'association_class' method because the association is broken
        # so we just want to move on and find the record manually
      end

      history_model_class = history_model.to_s.camelize.constantize
      history = history_model_class.where({
        can_be_details_id: self.id,
        can_be_details_type: self.class.name.underscore
      }).first

      can_be_model_class = can_be_model.to_s.camelize.constantize
      can_be_model_class.find(history.can_be_model_id)
    end
  end
end