【发布时间】:2016-03-04 04:50:29
【问题描述】:
我有一个 PORO TutorProfileHandler,它有一个函数 json,它返回一个哈希值。
class TutorProfileHandler
def initialize(opts)
@profile = opts[:tutor_profile]
end
def json
tutor = @profile.tutor
return {
id: tutor.id,
first_name: tutor.first_name,
last_name: tutor.last_name.first + '.',
school: @profile.school,
avatar: @profile.avatar.url,
bio: @profile.bio,
academic_level: @profile.academic_level,
headline: @profile.headline,
major: @profile.major,
rate: @profile.rate,
rating: @profile.rating,
courses: JSON.parse(@profile.courses),
video_url: @profile.video_url
}
end
end
在我的index_tutor_profiles.json.jbuilder,我想生成
{
tutor_profile: [{id: 1, ...}, {id: 2, ...}, ...],
tutor_sum: 20
}
但是当我这样做时
json.tutor_profiles (@tutor_profiles) do |profile|
TutorProfileHandler.new({tutor_profile: profile}).json
end
json.tutor_sum @tutor_sum
它给了我一个tutor_profiles 的空数组。
但是,如果我将所有内容从 TutorProfileHandler.json 移动到 jbuilder 文件,它就可以工作。如何在 jbuilder 数组中显式包含 TutorProfileHandler.json 返回的哈希?
注意:这会返回一个数组,但会创建一个新的键值对array:
json.tutor_profiles json.array(@tutor_profiles) do |profile|
TutorProfileHandler.new({tutor_profile: profile}).json
end
结果:
{
array: [{id: 1, ...}, {id: 2, ...}, ...],
tutor_profile: [],
tutor_sum: 20
}
【问题讨论】:
-
json 构建器是 DSL。一个人不应该将哈希传递给构建器,一个人应该明确声明像
last_name @profile.last_name这样的DSL。 -
@mudasobwa 如果我也有一个具有相同键值对的
show_tutor_profile.json.jbuilder,那么干的方法是什么? -
我自己从未使用过 builder,因为我没有找到优雅的 DRY 模式。可能唯一的方法是有一个 lambda,它在准备好的哈希上调用
public_send key, value。顺便说一句,hash.to_json有什么问题?
标签: ruby-on-rails ruby json jbuilder