加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 使用Ruby on Rails模块的建议

发布时间:2020-12-17 03:44:44 所属栏目:百科 来源:网络整理
导读:我正在使用 Ruby on Rails 3,我知道在哪种情况下使用模块是好的. 我有一个控制器,包括我以这种方式使用的许多私有方法: class UsersController ApplicationController def update params[:option1] = get_user_option1 params[:option2] = get_user_option2
我正在使用 Ruby on Rails 3,我知道在哪种情况下使用模块是好的.

我有一个控制器,包括我以这种方式使用的许多私有方法:

class UsersController < ApplicationController

  def update
    params[:option1] = get_user_option1
    params[:option2] = get_user_option2


    if params[:option2]
      params[:saving_success] = update_user
    end

    ...

    if params[:saving_success] 
      flash[:notice] = another_method_1
    else
      flash[:error] = another_method_2
    end
  end


    private

      def update_user
        if params[:option1] == something
          @user.save
        end
      end

      def another_method_1
        params[...] = ...
      ...
  end

正如您所看到的,在私有方法中,我有ActiveRecords和params方法之类的东西.我知道在模块中你不能直接使用那些ActiveRecords或params方法,但你可以将它们作为参数传递,如下例所示:

# In the controller file
class UsersController < ApplicationController
  include Users

  def update
    params[:option] = "true"
    @users = Users.find(1)
    Users::Validations.name (@user,params[:option])
    ...
  end
end

# In the module file
module Users
  module Validations
    def Validations.name(user,param)
      user == "Test_name" if param
      # Normally the following is not possible:
      # @user == "Test_name" if params[:option]
    end
  end
end

那么,在我的案例中你有什么建议?使用单独的模块是否好?

次要问题(目前……):

>性能怎么样?

附: I:不要注意示例的简单性.编写它们只是为了理解我传递ActiveRecords和params方法的困境.

附: II:如果您需要其他信息,请告诉我.

解决方法

模块有两个主要目的:

>命名空间
> Mixins

模块命名空间通常用于更好地组织代码并促进更安全和一致的范围.

但模块主要用作mixins.它的Ruby提供多重继承的方式.例如,假设您有跨类访问的方法(例如跨不同的模型/控制器等).不必在每个类中重复那些不一定只适用于该类的方法,而是将这些方法抽象出来并将其抽象到模块中,并在适当的类中包含或扩展模块.

这取决于模块与app目录的紧密耦合程度来决定
?存储模块的位置.存储模块中的一些模式:

> / lib目录,如果模块没有与app /特别“交互”.
> app / models目录,但可能会导致与实际的ActiveRecord模型混淆.
> 37 Signals introduced a pattern将它们视为“关注点”并将其存储在app / Concer中.

但是,如果您有一个仅用于用户控制器的方法,建议您将该代码放入用户模型中,因为这就是“用户”的业务逻辑所在的位置.

通过’ActiveRecords’,我假设您的意思是模型类(例如用户).
您可以在模块中访问模型类并对它们执行ActiveRecord操作(例如User.find(:all)).

但是,正如你猜对了,你不能使用params,你必须将它作为参数传递给模块的方法.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读