Skip to content

Instantly share code, notes, and snippets.

@sebastianvirlan
Last active April 27, 2018 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sebastianvirlan/167809c3e4721788cde2245a45b5aaf0 to your computer and use it in GitHub Desktop.
Save sebastianvirlan/167809c3e4721788cde2245a45b5aaf0 to your computer and use it in GitHub Desktop.
Generate Options straight from the Model for using them with html select options.
module SelectOptions
extend ActiveSupport::Concern
FIRST_OPTION = %w[All default].freeze
class_methods do
def enum_select_options(enum_name)
define_singleton_method "#{enum_name}_select_options" do |method_params = { header: true }|
map = send(enum_name.to_s.pluralize).map { |k, _| [k.humanize, k]}
map.unshift(FIRST_OPTION) if method_params[:header]
map
end
end
def define_select_options(method_name, params = {})
define_singleton_method method_name do |method_params = { header: true, condition_params: nil }|
query = params[:conditions]&.call(*method_params[:condition_params]) || all
map = query.map { |cp| [cp.send(params[:text]), cp.send(params[:value])] }
map.unshift(FIRST_OPTION) if method_params[:header]
map
end
end
end
end
# MODEL USAGE
class User
include SelectOptions
define_select_options :select_options, value: :id, text: :full_name, conditions: -> { ascending.enabled }
end
# EXAMPLE
def user_select_options
User.select_options
end
# MODEL USAGE WITH PARAMETER ON CONDITIONS
class User
include SelectOptions
define_select_options :select_options, value: :id, text: :full_name, conditions: lambda { |teacher_id|
joins(:courses).where(courses: { teacher_id: teacher_id } ).order('users.first_name asc')
}
end
# EXAMPLE
def user_select_options
User.select_options(condition_params: 5)
end
# MODEL USAGE FOR ENUMS
class User
include SelectOptions
enum status: %i[
pending enrolled graduated completed
]
enum_select_options :status
end
# EXAMPLE
def user_status_options
User.status_select_options
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment