简体   繁体   中英

Ruby Mixins and Instance variables

Is there a best practice way to pass params to mixed-in methods?

The class using the mixin could set up instance variables which mixed-in methods expect, or it could pass all necessary params as arguments to mixed-in methods.

The background to this is that we have a Rails controller which does publishing of content - but other controllers and even Models need to be able to "act as publshers" so I'm factoring the controllers methods into a Module which I'll mixin as needed.

Here, for example, is code from a Rails Controller which needs to "act as publisher" and it calls a mixed-in method question_xhtml()...

def preview
    @person = Person.find params[:id]
    @group = Group.find params[:parent_id]
    @div = Division.find params[:div_id]
    @format = 'xhtml'
    @current_login = current_login
    xhtml = person_xhtml() # CALL TO MIXED-IN METHOD
    render :layout => false
end

Ultimately question_xhtml needs all that stuff! Is this approach reasonable, or would it be better to do

def preview
    person = Person.find params[:id]
    group = Group.find params[:parent_id]
    div = Division.find params[:div_id]
    format = 'xhtml'
    xhtml = person_xhtml(person, group, div, format) # CALL TO MIXED-IN METHOD
    render :layout => false
end

...or something else?

I think you should be able to do:

module ActAsPublisher
  def person_xhtml
    do_stuff_with(@person, @group, @div, @format, @current_login)
    # eg. use instance variable directly in the module
  end
end

class WhateverController < Application Controller
  act_as_publisher
  ...
end

if you used script/generate plugin act_as_publisher.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM