我正在创建一个类用户,其中对象将具有变量" Permissions"基于帐户类型。我使用JSON文件来定义帐户类型和权限之间的映射。
但是每次我运行这个类的新实例时,我都会得到一个空白的权限值。
require 'json'
class User
attr_accessor :name, :email, :account_type, :permissions
def initialize(*args)
@name = args[0]
@email = args[1]
@account_type = args[2]
@permissions = User.get_permissions
end
def self.get_permissions
permissions_file = File.read("permissionsMap.json")
permissions_map = JSON.parse(permissions_file)
permissions_map[@account_type]
end
def print_details
puts @name
puts @email
puts @account_type
puts @permissions
end
end
这是JSON文件:
{
"employee": {
"accounts": "read",
"approve headcount": "no",
"manage finance": "yes"
},
"accountant": {
"accounts": "write",
"approve headcount": "no",
"manage finance": "yes"
},
"manager": {
"accounts": "read",
"approve headcount": "yes",
"manage finance": "no"
}
}
这就是我正在初始化User类实例的地方
require 'pp'
require 'json'
require_relative 'User'
puts "The runner starts now"
user_x = User.new("ABC","abc@def.com","manager")
user_x.print_details
答案 0 :(得分:0)
您需要将account_type数据传递给get_permissions方法才能使其正常工作:
def initialize(*args)
@name = args[0]
@email = args[1]
@account_type = args[2]
@permissions = User.get_permissions(@account_type)
end
从那里你只需稍微改变一下方法:
def self.get_permissions(acct_type)
permissions_file = File.read("permissionsMap.json")
permissions_map = JSON.parse(permissions_file)
permissions_map(acct_type)
end
如上所述,范围与您编写的方式不同。另外,另一条评论是正确的,初始化应该结构为:
def initialize(name, email, account_type)
@name = name,
@email = email,
@account_type = account_type
@permissions = User.get_permissions(account_type)
end
如果字段是可选字段,则始终可以使用= nil:
def initialize(name=nil, email=nil, account_type=nil)
答案 1 :(得分:0)
另一个答案发生在我身上,可能对你有用。
def initialize(name=nil, email=nil, account_type=nil)
@name = name
@email = email
@account_type = account_type
@permissions = get_permissions
end
def get_permissions
permissions_file = File.read("permissionsMap.json")
permissions_map = JSON.parse(permissions_file)
permissions_map[@account_type]
end
当你在User实例上调用print_details方法时,这也会给你@permissions。
希望这个答案也有帮助。