Skip to content

Commit

Permalink
move query methods override to its place
Browse files Browse the repository at this point in the history
  • Loading branch information
hzamani committed Aug 5, 2014
1 parent 7346884 commit b7104e5
Show file tree
Hide file tree
Showing 4 changed files with 15 additions and 24 deletions.
2 changes: 2 additions & 0 deletions lib/active_record/acts_as.rb
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
require 'active_support'
require 'active_record'
require 'active_record/acts_as/version'
require 'active_record/acts_as/relation'
require 'active_record/acts_as/migration'
Expand Down
30 changes: 10 additions & 20 deletions lib/active_record/acts_as/querying.rb
Original file line number Diff line number Diff line change
@@ -1,35 +1,25 @@

module ActiveRecord
module ActsAs
module Querying
def where(opts = :chain, *rest)
if opts.is_a? Hash
opts, acts_as_opts = opts.partition { |k,v| attribute_names.include?(k.to_s) }
opts, acts_as_opts = Hash[opts], Hash[acts_as_opts]
opts[acting_as_model.table_name] = acts_as_opts
end
super(opts, *rest)
end

def find_by(*args)
where(*args).take
end

def find_by!(*args)
where(*args).take!
module QueryMethods
def where_with_acts_as(opts = :chain, *rest)
if acting_as? && opts.is_a?(Hash)
opts, acts_as_opts = opts.stringify_keys.partition { |k,v| attribute_method?(k) }
opts, acts_as_opts = Hash[opts], Hash[acts_as_opts]
opts[acting_as_model.table_name] = acts_as_opts unless acts_as_opts.empty?
end
where_without_acts_as(opts, *rest)
end
alias_method_chain :where, :acts_as
end

class Relation
alias_method :scope_for_create_without_acting_as, :scope_for_create

def scope_for_create
def scope_for_create_with_acts_as
@scope_for_create ||= if acting_as?
where_values_hash.merge(where_values_hash(acting_as_model.table_name)).merge(create_with_value)
else
where_values_hash.merge(create_with_value)
end
end
alias_method_chain :scope_for_create, :acts_as
end
end
1 change: 0 additions & 1 deletion lib/active_record/acts_as/relation.rb
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ def acts_as(name, scope = nil, options = {})
alias_method :acting_as=, "#{name}=".to_sym

include ActsAs::InstanceMethods
extend ActsAs::Querying
end

def acting_as?(other = nil)
Expand Down
6 changes: 3 additions & 3 deletions spec/acts_as_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -179,9 +179,9 @@
end

it "includes supermodel attributes in Relation.scope_for_create" do
relation = Pen.where(name: 'new name')
expect(relation.scope_for_create.keys).to include(:name)
expect(relation.scope_for_create[:name]).to eq('new name')
relation = Pen.where(name: 'new name', price: 1.4, color: 'red')
expect(relation.scope_for_create.keys).to include('name')
expect(relation.scope_for_create['name']).to eq('new name')
end
end

Expand Down

0 comments on commit b7104e5

Please sign in to comment.