diff --git a/CHANGELOG.md b/CHANGELOG.md index 5c4aca0..24b38ac 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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) diff --git a/lib/active_force/active_query.rb b/lib/active_force/active_query.rb index 2c232d8..242e885 100644 --- a/lib/active_force/active_query.rb +++ b/lib/active_force/active_query.rb @@ -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=[]) @@ -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 diff --git a/spec/active_force/active_query_spec.rb b/spec/active_force/active_query_spec.rb index cd73137..c990743 100644 --- a/spec/active_force/active_query_spec.rb +++ b/spec/active_force/active_query_spec.rb @@ -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