Assigning variables in view is generally not recommended. However, in this case you can use an inline assignment which is generally accepted (as long as you keep the usage scoped within the context of the condition block):
if (intro = clean_book_intro_component(:literary_works)).present?
%h2 Other Books Related to #{@book.title}
%p.fact-text
= intro
Another solution is to memoize the value inside the function.
def clean_book_intro_component(component)
@component ||= {}
@component[component] ||= sanitize @book.intro.send(component), tags: %w(span b i p a), attributes: %w(id class style href)
end
However, this will cause the interpreter to retain the data as long as there is a reference to the instance. Therefore, this is recommended only in very particular cases where the execution is expensive and/or the data to be memoized is limited.
Moreover, it requires some extra complications if the helper accepts parameters. In fact, you will end up memoizing an amount of data which is linear with the possible input of the parameters.
clean_book_intro_component(:literary_works)twice? Is it an expensive method?