Rails helper method with external classes -
i going try , explain best way can...so here go...
here old(working) controller truck. sorts columns , asc/desc orders works intended.
class truckscontroller < applicationcontroller # /trucks # /trucks.json require 'sort_methods' helper_method :sort_column, :sort_direction def index @trucks = truck.search(params[:search]).order(sortmethods.sort_column(truck, "truck_no", params[:sort]) + " " + sortmethods.sort_direction(params[:direction])) respond_to |format| format.html # index.html.erb format.json { render json: @trucks } end end private def sort_column truck.column_names.include?(params[:sort]) ? params[:sort] : "truck_no" end def sort_direction %w[asc desc].include?(params[:direction]) ? params[:direction] : "asc" end end from understand helper_method here called when page passed no arguments, has default can revert , sort methods below methods cause default behavior. works intended, can load pages , sort.
now @ trucks calling class in lib has identical methods sort_methods because call methods multiple times , i'm trying dry code this. works, still because i've done class in way:
class sortmethods def self.sort_column(table, field, sort) table.column_names.include?(sort) ? sort : field end def self.sort_direction(direction) %w[asc desc].include?(direction) ? direction : "asc" end end alright code works intended, problem repeating sort methods twice, in controller , in sortmethods class. set default helper class using sortmethods if try call using code:
helper_method :sortmethods.sort_column(truck, "truck_no", params[:sort]), sortmethods.sort_direction(params[:direction]) i receive following message:
undefined local variable or method `sort_column' #<#<class:0x1a3a780>:0x1852f08> my assumption 1 of variables passing in nil, can't figure out 1 , how go avoid problem? there way can default if no parameters set in place. tried moving helper in index gives me error:
undefined method `sort_column' :sortmethods:symbol
helper_method makes given method accessible inside controller views. hence, don't need specify sortmethods methods helper, because not part of controller. should able call them in view like
sortmethods.sort_column(blah) also, keep definition of sortmethods class? if in file sort_methods.rb anywhere in app folder, can skip require on top, rails automatically search (it part of constant_missing method)
Comments
Post a Comment