Skip to content

Check for existing vault_line (eg. vault declaration) on add generator #10

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

Merged
merged 1 commit into from
Jun 3, 2025
Merged
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
27 changes: 23 additions & 4 deletions lib/generators/rails_vault/add_generator.rb
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,30 @@ def create_vault_file
end

def inject_vault_into_model
parent_class = class_name.split("::").first
has_existing_vault? ?
gsub_file(model_path, /^\s*vaults?\s+.+$/, vault_line) :
inject_into_class(model_path, class_name.deconstantize) { "#{vault_line}\n" }
end

private

def has_existing_vault?
model_content =~ /vaults?\s+/
end

def vault_line
vaults = Set.new(model_content[/vaults?\s+(.+)$/, 1]&.scan(/:(\w+)/)&.flatten || []) << plural_name
method_name = vaults.many? ? "vaults" : "vault"

" #{method_name} #{vaults.map { ":#{_1}" }.join(", ")}"
end

def model_content
@model_content ||= File.binread(model_path)
end

inject_into_class "app/models/#{class_path.join("/")}.rb", parent_class do
" vault :#{plural_name}\n"
end
def model_path
"app/models/#{class_path.join("/")}.rb"
end
end
end
Expand Down