Skip to content

Instantly share code, notes, and snippets.

@bsharpe
Created June 22, 2017 19:39
Show Gist options
  • Save bsharpe/257e71627cb4ccdf26e6221fa8b422a6 to your computer and use it in GitHub Desktop.
Save bsharpe/257e71627cb4ccdf26e6221fa8b422a6 to your computer and use it in GitHub Desktop.
The most useful module for Rails controllers
module BasicMemberSupport
extend ActiveSupport::Concern
protected
def find_member(id)
@member = collection.find(id)
end
def build_member(attrs = nil)
@member = begin
if member_is_one?
collection.send(controller_name.singularize) || collection.send("build_#{controller_name.singularize}")
else
collection.respond_to?(:new) ? collection.new(attrs) : collection.build(attrs)
end
end
end
def member_association
@_member_association ||= begin
if collection.class.respond_to?(:reflect_on_association)
collection.class.reflect_on_association(controller_name.singularize)&.macro
end
end
end
def member_is_one?
member_association == :has_one
end
def member
@member ||= begin
if member_is_one?
model_name = controller_name.singularize
collection.send(model_name) || collection.send("build_#{model_name}")
else
params[:id] ? find_member(params[:id]) : build_member
end
end
end
def member=(new_value)
@member = new_value
end
def collection
@collection ||= controller_name.classify.constantize
end
def collection=(new_value)
@collection = new_value
end
def current_page
collection.page(page_number)
end
def page_number
params[:page] ? params[:page][:number] : 1
end
end
@bsharpe
Copy link
Author

bsharpe commented Jun 22, 2017

an example of usage:

class NotesController < ApplicationController
    include BasicMemberSupport

    def index
      render json: collection
    end

    def create
      member = build_member(note_attributes)
      member.save!
      render json: member, status: :created
    end

    def update
      member.update!(note_attributes)
      render json: member
    end

    def show
      render json: member
    end

    def destroy
      member.destroy!
      render json: member
    end

    private

      def note_attributes
        params.permit(
          :body,
          :title
        )
      end
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment