Skip to content

Instantly share code, notes, and snippets.

@davidtolsma
Last active June 25, 2020 00:05
Show Gist options
  • Save davidtolsma/b59c85845a76b47d0cb94dc88f340d28 to your computer and use it in GitHub Desktop.
Save davidtolsma/b59c85845a76b47d0cb94dc88f340d28 to your computer and use it in GitHub Desktop.
Rails Template:
# rails app:template LOCATION='https://gist.github.com/davidtolsma/b59c85845a76b47d0cb94dc88f340d28'
def ask_with_default(prompt, default)
value = ask("#{prompt} (default: #{default})")
value.present? ? value : default
end
run "bundle add 'friendly_id'"
rails_command "generate friendly_id"
while yes?("Do you want to use Friendly ID with an existing model?") do
model_name = ask_with_default("Model Name:", "Post")
attribute = ask_with_default("Attribute:", "name")
if model_name && attribute
# We generate a migration to add the friendly id slug column.
generate(:migration, "AddSlugTo#{model_name.titleize.pluralize}", "slug:uniq")
string = <<~RUBY
extend FriendlyId
friendly_id :#{attribute}, use: :slugged
RUBY
# Inject the friendly id methods into the class.
inject_into_file "app/models/#{model_name.downcase}.rb", string, after: "class #{model_name.titleize} < ApplicationRecord\n"
end
end
# Run migrations for newly generated migrations
rails_command "db:migrate"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment