Skip to content

Commit

Permalink
Allow set to take a lambda
Browse files Browse the repository at this point in the history
  • Loading branch information
jrmhaig committed Jun 30, 2024
1 parent 0aa39c8 commit 65b72d0
Show file tree
Hide file tree
Showing 4 changed files with 29 additions and 1 deletion.
9 changes: 9 additions & 0 deletions docs/pre_processing_fields.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,15 @@ Set a field to a given value.
end
```

The field may be set to the return value of a lambda, so to set a field to the
current time:

```ruby
amoeba do
set datetime_field: ->() { Time.now }
end
```

## regex

To do
Expand Down
2 changes: 1 addition & 1 deletion lib/amoeba/cloner.rb
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ def process_null_fields
def process_coercions
# prepend any extra strings to indicate uniqueness of the new record(s)
amoeba.coercions.each do |field, coercion|
@new_object[field] = coercion.to_s
@new_object[field] = coercion.is_a?(Proc) ? coercion.call : coercion.to_s
end
end

Expand Down
17 changes: 17 additions & 0 deletions spec/lib/amoeba/class_methods_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,23 @@

it { expect(dup.test_field).to be(false) }
end

context 'with a datetime field set by a lambda' do
let(:params) { { test_field: DateTime.parse('30 Jun 2024 18:19') } }
let(:field_type) { :datetime }
let(:config) do
<<~CONFIG
amoeba do
set test_field: ->() { Time.now }
end
CONFIG
end

before { travel_to DateTime.parse('1 Jul 2024 09:35') }
after { travel_back }

it { expect(dup.test_field).to eq(DateTime.parse('1 Jul 2024 09:35')) }
end
end
end
end
2 changes: 2 additions & 0 deletions spec/spec_helper.rb
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
end

require 'active_record'
require 'active_support/testing/time_helpers'
require 'amoeba'

adapter = if defined?(JRuby)
Expand All @@ -32,6 +33,7 @@
ActiveRecord::Base.establish_connection(adapter: adapter, database: ':memory:')

::RSpec.configure do |config|
config.include ActiveSupport::Testing::TimeHelpers
config.order = :defined
end

Expand Down

0 comments on commit 65b72d0

Please sign in to comment.