I want to DRY my views and controllers from a lot of similar code. I want to do it by myself in educational purpose, I know about the InheritedResourse gem. So far I wrote:
class Admin::ResourcesController < Admin::AdminBaseController
before_filter :get_model_name
def index
result = @model.all #Resource.all
instance_variable_set "@#{@@collection_resource_name}", result # @resources = result
result # return it duo it can be used with super
end
def show
result = @model.find(params[:id])
instance_variable_set "@#{@@instance_resource_name}", result
result
end
protected
@@collection_resource_name = 'resources'
@@instance_resource_name = 'resource'
def self.set_resource_name(hash)
@@instance_resource_name = hash[:instance_resource_name]
@@collection_resource_name = hash[:collection_resource_name]
end
private
def get_model_name
@model = controller_name.classify.constantize # Resource
end
end
Only two actions, but you got the idea: abstract any model to a 'resource', set a list of model fields (or get it dynamicaly) and that's it.
First of all, I think instead of @@instance_resource_name (class variable), I need a class instance variable. I'm right?
... but, it is not a main question. I think that it's cool when this kind of code is wrapped in mixin. Because in my example it is Admin::ResourceController, but I can also have a User::ResourceController or just something another.
Ok, I wrapped it in a mixin. For usability, I want to call something like actions only: [:index, :show]
in controller in section, where I put before_filter
, for example.
How this section of code is called? Class instance?
Ok, the example:
require 'active_support/concern'
module ScaffoldResources
extend ActiveSupport::Concern
included do
def hello
self.class.action_list
end
end
module ClassMethods
@action_list = [:new, :show, :index, :edit, :update, :destroy, :create]
attr_accessor :actions_list
def actions(*params)
@actions_list = params
end
end
end
For testing, I create this small controller:
class Admin::UsersController < Admin::ResourcesController
include ScaffoldResources
@actions_list = 'hard set'
actions 'some','actions','i think'
def show
render json: hello
end
end
So, when I call hello method (it do only self.class.action_list
) I want to see anything. I set class instance variable in mixin and in class – hardcode and through method defined in mixin. But it's nil!
I think you got the idea, what I'm trying to achieve. How it can be achieved?