Ruby metaprogramming inside model
I have a model called Snippet, which contains snippets of HTML to push into views.
The model has a column CODE and another CONTENT
I'd like to write something like this in my view and get the content back
<%= raw Snippet.PHONE_NUMBER %>
which looks up PHONE_NUMBER on CODE and returns CONTENT
Add a method_missing
class method in Snippet
class as follows
# Snippet class
class << self
def method_missing(method, *args, &block)
if(snippet = Snippet.find_by_code(method.to_s))
return snippet.content
else
return super(method, *args, &block)
end
end
end
This should do the trick.
However, on a related note, I'm not sure if doing this would be the best way to go because your code is dependent on the data in your database. Tomorrow, the record for phone number gets removed and your code Snippet.PHONE_NUMBER
would break. There is a lot maintenance headache in this approach.
A cleaner approach (which would avoid metaprogramming) would have your view do something like this:
<%= snippet :PHONE_NUMBER %>
or
<%= snippet 'PHONE_NUMBER' %>
where the snippet
method is defined in a helper module like this:
module SnippetHelper
def snippet(code)
raw Snippet.find_by_code(code.to_s).content
end
end
and made available to all your views with something like this:
class ApplicationController < ApplicationController::Base
helper :snippet
end
Or use delegate.
But it sounds like you're providing another implementation of partials, or helpers, or a combination of decent_exposure
and some combination of helpers and partials.
精彩评论