我有一个很难解决的问题。
我想复制title_with_if_statement
方法的结果,但要使用title
方法中使用的语法。但是,我不知道要在enforce_policy_to_level()
方法中添加什么来完成此操作。
我可以执行'title_less_可读性',但是由于该策略位于顶部,因此我发现title方法更具可读性,并且由于我将针对数百种方法进行此操作,因此我希望保持其DRY和可读性。 / p>
有什么建议吗?
这甚至可能吗?基本上,这是一个before_action,但是使用方法本身的结果。
class Car
def title
enforce_policy_to_level(1)
# Code that returns the "Car Title" string
"Car Title"
end
def title_less_readable
# Code that returns "Car Title" string
content = "Car Title"
return secure_text(content) unless authorized_to_level?(1)
content
end
def title_with_if_statement
# Code that returns the "Car Title" string
content = "Car Title"
if authorized_to_level?(1)
content
else
secure_text(content)
end
end
private
def enforce_policy_to_level(level)
# Return from title method with the secured result of title method
# if it's not authorized. In this example it would be secure_text('Car Title')
# which output return '---------'
# If if authorized,just continue with how title method would normally return
end
def authorized_to_level?(level)
current_user_level = 1 # Dynamic from user record
current_user_level >= level
end
def secure_text(text)
'X' * text.length
end
end