integrate rails modules with javascript objects
Courtenay : February 23rd, 2006
This is a fancy one for you dry-configuration-heads out there.
First up, lets say you're storing digital assets in a rails app, and you want the user to enter what sort of content-type it is: image, video, html, whatever, when (before) they upload the file. So, you want to fill in a text-box with a suitable default after they select the file on their system.
And, to make matters more interesting, you want to use the same regex on the filename on the server-side as you do on the client-side.
First up, let's assume that the extension of the file is, indeed, indicative of the content-type. So, open up environment.rb (gasp!) and make yourself a configuration module for your app. Please note, if you have a better way of doing this, let me know; I'm too busy to trawl Martin Fowler's bliki for the correct pattern here, people! Please note, some highly questionable ruby code follows.
(I wrote this as a module because I don't really want to instantiate the config object. Again, feel free to correct me. Also, I'm defining these values in methods, because I have some more that actually take arguments.)
module MyApp
module Config
class << self
#define a bunch of regexes
def image_tags
/jpg|gif|png|tif|eps/
end
def document_tags
/pdf|doc|xls|txt/
end
def movie_tags
/mov|qt|qt3/
end
end
end
end
In your view, you want something like this: (make sure it's multipart!)
Some explanation:
- I bind the element_file to that anonymous function so I can use 'this'. Just 'coz I love that little sucker.
- We iterate over all the class (singleton) methods in Config; you may like to subclass it further, like Config::ContentTypes or something.
- I use 'inspect' so it gives a JS-happy regex
This allows us to use the same regexes on server and client-side.
Possible changes:
- use instance variables, or something
- use JSON
- use Behavior
1 Response to “integrate rails modules with javascript objects”
Leave a Reply
Remember: escape your underscores \_ and indent code at least 4 spaces or incur the wrath of smartypants.
May 17th, 2007 at 05:09 AM
interesting