开发者

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜