Skip to content

Commit

Permalink
Adding order method to active query to support several argument forma…
Browse files Browse the repository at this point in the history
…ts (#58)

* add order method to support diff argument formats

* updated the changelog

* updated the change log
  • Loading branch information
swpreethi authored May 26, 2023
1 parent 17cd43a commit 22c4cfb
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 0 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

## Not released

- Add `#order` method to active query that accepts arguments in several formats ( symbol, string that has raw soql) (https://github.com/Beyond-Finance/active_force/pull/58)

## 0.14.0

- Add `scoped_as` option to `has_one` association (https://github.com/Beyond-Finance/active_force/pull/50)
Expand Down
23 changes: 23 additions & 0 deletions lib/active_force/active_query.rb
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,11 @@ def loaded?
!@records.nil?
end

def order *args
return self if args.nil?
super build_order_by args
end

private

def build_condition(args, other=[])
Expand Down Expand Up @@ -209,5 +214,23 @@ def clone_self_and_clear_cache
new_query.instance_variable_set(:@records, nil)
new_query
end

def build_order_by(args)
args.map do |arg|
case arg
when Symbol
mappings[arg].to_s
when Hash
arg.map { |key, value| "#{mappings[key]} #{order_type(value)}" }
else
arg
end
end.join(', ')
end

def order_type(type)
type == :desc ? 'DESC' : 'ASC'
end

end
end
21 changes: 21 additions & 0 deletions spec/active_force/active_query_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -335,4 +335,25 @@
it { is_expected.to be_truthy }
end
end

describe "#order" do
context 'when it is symbol' do
it "should add an order condition with actual SF field name" do
expect(active_query.order(:field).to_s).to eq "SELECT Id FROM table_name ORDER BY Field__c"
end
end

context 'when it is string - raw soql' do
it "should add an order condition same as the string provided" do
expect(active_query.order('Field__c').to_s).to eq "SELECT Id FROM table_name ORDER BY Field__c"
end
end

context 'when it is multiple columns' do
it "should add an order condition with actual SF field name and the provided order type" do
expect(active_query.order(:other_field, field: :desc).to_s).to eq "SELECT Id FROM table_name ORDER BY Other_Field, Field__c DESC"
end
end

end
end

0 comments on commit 22c4cfb

Please sign in to comment.