简体   繁体   中英

convert a ruby rails model class into a class in the lib folder

I have the following model/Admin.rb class that I would like to extract and convert into a lib/UserApi class. I am not familiar into creating lib classes and being able to call them from my controllers. Any advice appreciated.

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

end

This is what I currently use in the auth_controller"

class Admin::AuthController < Admin::BaseController

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

Create the UserApi class in the lib directory:

# lib/user_api.rb
class UserApi
 ...

Update the controller:

class Admin::AuthController < Admin::BaseController

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

Load the classes you put in your lib/ directory, so they are accessible in the controller: Best way to load module/class from lib folder in Rails 3?

I typically create a config/initializers/00_requires.rb file and require the lib files I need.

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