module NullObjectAssociations::SingletonMethods

Public Instance Methods

belongs_to(name)
Alias for: has_one
empty?() click to toggle source
# File lib/null_object_associations.rb, line 16
def empty?; true; end
has_and_belongs_to_many(name, actions = {})
Alias for: has_many
has_many(name, actions = {}) click to toggle source
# File lib/null_object_associations.rb, line 19
def has_many(name, actions = {})
  if actions[:respond_to] == :any
    associations = [] 
    associations.extend ArrayMethodMissing
  else
    actions = coerce_actions(actions)
    associations = build_associations(actions)
  end


  define_method(name) do
    associations
  end
end
Also aliased as: has_and_belongs_to_many
has_one(name) click to toggle source
# File lib/null_object_associations.rb, line 35
def has_one(name)
  define_method(name) { nil }
end
Also aliased as: belongs_to
method_missing(to_be_called, *args) click to toggle source
# File lib/null_object_associations.rb, line 8
def method_missing(to_be_called, *args)
  if args.empty?
    []
  else
    nil
  end
end

Private Instance Methods

build_associations(actions) click to toggle source
# File lib/null_object_associations.rb, line 53
def build_associations(actions)
  empty_array = []
  noa = NullObjectForArgument.new
  methods_with_arguments = [:pluck, :limit, :order]

  empty_array.tap do |empty_arr|
    actions.each do |action|
      empty_arr.define_singleton_method(action) do |*args|
        if methods_with_arguments.include?(action) && !args.empty?
          return noa
        end

        []
      end
    end
  end
end
coerce_actions(actions) click to toggle source
# File lib/null_object_associations.rb, line 42
def coerce_actions(actions)
  case actions[:respond_to]
  when Array, nil
    actions = Array(actions[:respond_to])
  else
    actions = *actions[:respond_to]
  end

  actions
end