Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

More robust location definitions #93

Merged
merged 3 commits into from
Jan 9, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions lib/oaken.rb
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,12 @@ def load_onto(seeds) = @entries.each do |path|
seeds.class_eval path.read, path.to_s
end
end

def self.definition_location
# Trickery abounds! Due to Ruby's `caller_locations` + our `load_onto`'s `class_eval` above
# we can use this format to detect the location in the seed file where the call came from.
caller_locations(2, 8).find { _1.label.match? /block .*?load_onto/ }
end
end

def self.prepare(&block) = Seeds.instance_eval(&block)
Expand Down
12 changes: 7 additions & 5 deletions lib/oaken/stored/active_record.rb
Original file line number Diff line number Diff line change
Expand Up @@ -49,11 +49,13 @@ def upsert(label = nil, unique_by: nil, **attributes)
#
# Note: `users.method(:someone).source_location` also points back to the file and line of the `label` call.
def label(**labels)
# TODO: Fix hardcoding of db/seeds instead of using Oaken.lookup_paths
location = caller_locations(1, 6).find { _1.path.match? /db\/seeds\// }
labels.each { |label, record| _label label, record.id }
end

private def _label(name, id)
raise ArgumentError, "you can only define labelled records outside of tests" \
unless location = Oaken::Loader.definition_location

labels.each do |label, record|
class_eval "def #{label} = find(#{record.id.inspect})", location.path, location.lineno
end
class_eval "def #{name} = find(#{id.inspect})", location.path, location.lineno
end
end
6 changes: 6 additions & 0 deletions test/dummy/test/models/oaken_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,12 @@ def self.column_names = []
assert_match "db/seeds/test/data/users.rb", users.method(:test_user).source_location.first
end

test "can't use labels within tests" do
assert_raise ArgumentError do
users.label kasper_2: users.kasper
end
end

test "updating fixture" do
users.kasper.update name: "Kasper2"
assert_equal "Kasper2", users.kasper.name
Expand Down
Loading