【问题标题】:convert a ruby rails model class into a class in the lib folder将 ruby​​ rails 模型类转换为 lib 文件夹中的类
【发布时间】:2013-07-30 14:15:27
【问题描述】:

我有以下模型/Admin.rb 类,我想将其提取并转换为 lib/UserApi 类。我不熟悉创建 lib 类并能够从我的控制器中调用它们。任何建议表示赞赏。

class Admin
attr_accessor :id
attr_accessor :firstname
attr_accessor :lastname
attr_accessor :usergroups

def initialize json_attrs = {}
    @usergroups = []
    unless json_attrs.blank?
        @id = json_attrs["id"]
        @fname = json_attrs["fname"]
        @lname = json_attrs["lname"]
        @groups = json_attrs["groups"]
        @authenticated = true
    end
    if json_attrs.blank?
        @firstname = "blank"
    end
end

def is_authenticated?
    @authenticated ||= false
end

def in_groups? group_names
    return !(@usergroups & group_names).empty? if group_names.kind_of?(Array)
    @usergroups.include?(group_names)
end

def authenticate username, password
    options={:basic_auth => {:username => CONFIG[:API_CLIENT_NAME], 
                            :password => CONFIG[:API_CLIENT_PASSWORD]}}

    api_response = HTTParty.get("#{CONFIG[:API_HOST]}auth/oauth2?username=#{username}&password=#{password}", options)

    raise "API at #{CONFIG[:API_HOST]} is not responding" if api_response.code == 500 || api_response.code == 404

    if api_response.parsed_response.has_key? "error"
        return false
    else
        initialize(api_response.parsed_response["user"].select {|k,v| ["id", "fname", "lname", "groups"].include?(k) })
        @authenticated = true
        return true
    end
end

def full_name
    "#{@name} #{@name}"
end

结束

这是我目前在 auth_controller 中使用的"

class Admin::AuthController < Admin::BaseController

def auth
    admin_user = Admin.new
    auth_result = admin_user.authenticate(params[:username], params[:password])
end 

【问题讨论】:

    标签: ruby-on-rails ruby class shared-libraries


    【解决方案1】:

    在lib目录下创建UserApi类:

    # lib/user_api.rb
    class UserApi
     ...
    

    更新控制器:

    class Admin::AuthController < Admin::BaseController
    
    def auth
        admin_user = UserApi.new
        auth_result = admin_user.authenticate(params[:username], params[:password])
    end 
    

    加载您放在 lib/ 目录中的类,以便在控制器中访问它们:Best way to load module/class from lib folder in Rails 3?

    我通常会创建一个config/initializers/00_requires.rb 文件并需要我需要的 lib 文件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-02-18
      • 2012-04-27
      • 2021-01-04
      • 1970-01-01
      • 2018-05-27
      • 1970-01-01
      • 2020-08-10
      相关资源
      最近更新 更多