class SetBuilder::Set

Attributes

model[R]

Public Class Methods

new(model_or_scope, raw_data) click to toggle source
# File lib/set_builder/set.rb, line 6
def initialize(model_or_scope, raw_data)
  @model, @scope = get_model_and_scope(model_or_scope)
  @set = raw_data
end

Public Instance Methods

constraints() click to toggle source
# File lib/set_builder/set.rb, line 17
def constraints
  @constraints ||= get_constraints
end
perform() click to toggle source

Returns an instance of ActiveRecord::NamedScope::Scope which can fetch the objects which belong to this set

# File lib/set_builder/set.rb, line 45
def perform
  constraints.inject(@scope) {|scope, constraint| constraint.perform(scope)}
end
to_s() click to toggle source

Describes this set in natural language

# File lib/set_builder/set.rb, line 35
def to_s
  constraints.to_sentence
end
valid?() click to toggle source

Returns true if all of the constraints in this set are valid

# File lib/set_builder/set.rb, line 26
def valid?
  constraints.all?(&:valid?)
end

Private Instance Methods

get_constraints() click to toggle source
# File lib/set_builder/set.rb, line 55
def get_constraints
  @set.inject([]) do |constraints, line|
    negate, trait_name, args = false, line.first.to_s, line[1..-1]
    trait_name, negate = trait_name[1..-1], true if (trait_name[0..0] == "!")
    trait = model.traits[trait_name]
    raise("\"#{trait_name}\" is not a trait for #{model}") unless trait
    constraints << trait.apply(*args).negate(negate)
  end
end
get_model_and_scope(model_or_scope) click to toggle source

!todo: this can be overriden or factored out to allow SetBuilder

to be used with other ORMs like DataMapper
# File lib/set_builder/set.rb, line 69
def get_model_and_scope(model_or_scope)
  if defined?(ActiveRecord::NamedScope::Scope) && model_or_scope.is_a?(ActiveRecord::NamedScope::Scope)
    [model_or_scope.proxy_scope, model_or_scope]
  else
    # [model_or_scope, model_or_scope.scoped({})]
    [model_or_scope, model_or_scope.scoped]
  end
end