Skip to content

Instantly share code, notes, and snippets.

@samacs
Last active April 24, 2017 23:46
Show Gist options
  • Save samacs/cb28061ebdfa4fe7ca120c714e5299a6 to your computer and use it in GitHub Desktop.
Save samacs/cb28061ebdfa4fe7ca120c714e5299a6 to your computer and use it in GitHub Desktop.
module CrudManagement
extend ActiveSupport::Concern
module ClassMethods
def crudify(resource_name, model_name = nil, options = {})
model_name ||= resource_name
options[:plural_name] ||= resource_name.to_s.pluralize
options[:singular_name] ||= resource_name.to_s.singularize
options[:permitted_params] ||= []
options[:route_prefix] ||= ''
options[:scopes] ||= :all
options[:order] ||= {}
index_route = [options[:route_prefix],
options[:plural_name],
'path'].join('_')
if options[:scopes].respond_to?(:map)
options[:scopes].map { |scope| scope }.join('.')
end
code = %(
before_action :set_#{options[:singular_name]},
only: %i[edit update destroy show]
def index
@#{options[:plural_name]} = #{model_name.capitalize}.#{options[:scopes]}.order(#{options[:order]})
end
def new
@#{options[:singular_name]} = #{model_name.capitalize}.new
end
def create
@#{options[:singular_name]} = #{model_name.capitalize}.new(#{options[:singular_name]}_params)
if @#{options[:singular_name]}.save
redirect_to #{index_route},
success: "#{options[:singular_name].capitalize} saved successfully"
else
flash.now[:alert] = @#{options[:singular_name]}.errors.full_messages
render :new
end
end
def edit; end
def update
if @#{options[:singular_name]}.update(#{options[:singular_name]}_params)
redirect_to #{index_route},
success: "#{options[:singular_name].capitalize} saved successfully"
else
flash.now[:alert] = @#{options[:singular_name]}.errors.full_messages
render :new
end
end
def destroy
if @#{options[:singular_name]}.destroy!
redirect_to #{index_route}, success: '#{resource_name.capitalize} deleted'
else
redirect_to #{index_route}, alert: 'Could not delete the #{resource_name}'
end
end
private
def #{options[:singular_name]}_params
params.require(:#{options[:singular_name]}).permit(#{options[:permitted_params]})
end
def set_#{options[:singular_name]}
@#{options[:singular_name]} = #{model_name.capitalize}.find(params[:id])
end
)
logger.debug code
module_eval code, __FILE__, __LINE__
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment