SuperInPlaceControls: A new rails plugin from Flvorful
We just finished up our newest plugin: SuperInPlaceControls.
This is meant as a drop in replacement for the current in_place_edit_for method that was recently moved into a plugin. SuperInPlaceControls works with Rails 2.0, validations, and empty fields.
Check out the SuperInPlaceControls page for more info, demos, examples and docs.
Have fun.
—jake
New Open Source site launched
We have just launched our new Open Source project site. We will centralize all of our OS projects into this site.
Check it out
BetterFLV: An Alternative to Adobe's stock FLVPlayback Component
When we first created our software we had this great idea. Wouldn’t it be cool if we could let our users change their skins out. We looked everywhere for an example, the closest thing we found was Youtube’s custom color control, nothing on the order of being able to create their own buttons and background. So then we started looking deeper into the FLVPlayback component and saw that there was already a way to swap out skins. So, stupidly, we started coding, wondering why in the world anyone else hadn’t tried this technique before. Lo and behold, we found our answer. If the skin had more buttons and graphics than what was provided by Adobe, you couldn’t easily swap it out because of how the object got named. Most of you have probably seen this problem: You create an object (either via actionscript or dropping it on the stage) and when you trace the object name you get something useless like “instance129”. When this happens, you are not able to easily swap out the clips (or buttons) dynamically because you dont always know what the objects name is going to be. We tried everything, needless to say, nothing worked, so we started from scratch.
Introducing BetterFLV
We figured, if Adobe wasnt going to give us the control we were going to have to create a new Skin class and FLVPlayback Class, and that’s exactly what we did.
BetterFLV extends the FLVPlayback component and has a companion class called Skin that controls the skin for the BetterFLV object. This allows you to create sites that allow your users to create their own skin buttons and backgrounds.
We didnt stop there. You would think that a video player class would come with a built-in timer object, as most of you already know it doesnt, but BetterFLV does. It also contains the code for an “Embed Code” button so that you can share the video and it has a “Click-To-Seek” buffer so that you dont have to drag the handle to seek thru the video.
Best of all: It’s free.
We are releasing BetterFLV as open source (GPL)
How to use
We tried to make it as easy as possible.
- Download the code and copy Skin.as and BetterFLV.as to you project directory.
- import the classes into your flash app via
import BetterFLV - Create an object from BetterFLV:
main_player = new BetterFLV() - Tell the player what skin to use:
main_player.set_skin("http://www.somedomain.com/some_skin.swf") - Tell the player the source for the video:
main_player.source = "http://www.somedomain.com/some_flv.flv"
Done
Check out the sample folder for a sample app and sample skin.
Future Versions
- Add Volume Slider
- Anything else we can think of
Download the code and let us know what you think.
—jake
The most hilarious Rails post ever
I was browsing around DZone and found a post by Alex Bunardzic satirizing the now common “Why I switched from Rails to WHATEVER” posts that have been flying around the net. His language of choice: Assembler. Take a read and dont blame me if you fall out of your chair.
PS You must be a nerd to understand :)
—jake
Quick Zebra Striping in Rails 3
Striping table rows is usually a necessity when making accessible web pages. This can be a tedious task. Through the ages (and by ages I mean the last 10 years or so) there have been many ways to do this in many dynamic languages. Everything from taking the modulo of the index when iterating through the set, to flipping a counter back and forth.
Well, if you’re programming in rails, you get a much easier way to do it via the cycle method. Let me show you how easy it is:
<table>
<% @objects.each do |obj| %>
<tr class="<%= cycle("even", "odd") %>">
<td><%= obj.id %></td>
<td><%= obj.title %></td>
<tr>
<% end %>
</table>
Simplicity itself. Now as you loop through the set, it will cycle the class name of the row between “even” and “odd”. Now all you need to do is set CSS values for those classes and your done.
Here is a quick example of a CSS class for odd:
.odd{
background:#dedede;
}
Gotta love rails.
—jake
Rescuing Ruby 9
Now, before anyone goes crazy, this article has nothing to do with saving ruby from something, i just couldnt think of a better title. We will be talking about rescue and some cool tricks that can be done with it.
As most of you vets know, every thing in Ruby is an object. What most noobs dont realize is how powerful that can be and how concise your code can become. Of course, the flip side of that problem is what i call, newbie-come-expert. It’s basically the stage in a noob’s study of a language where they think they know enough to write really cool software. What actually happens is they end up with code like this:
@objects.map {|e| [e.id, e.title]}.sort {|a, b| a.last <=> b.last}.map {|e| e.join(" ")}.join("\n")
Lovely.
Dont worry noobs, everyone does it. I’m still trying to undo it from some of my older code.
Anyway, my point is, sometimes Ruby’s dynamicism (say that 3 times fast) can lead to messy code so use this tip wisely.
On to the actual tip.
So, like I said before, EVERYTHING in Ruby is an object, even the remains of a rescue clause or an inline rescue which is what we will be playing with here.
How many of you have done this:
@person = Person.find(some_id)
only to get the following error:
ActiveRecord::RecordNotFound: Couldn't find Person with ID=22
It’s pretty annoying, mainly because this type of thing could easily happen in a live app. A user goes to find something that isnt there. One way around it is to have a rescue at the end of the method, but what if you have multiple finds that could throw errors? What if you still need to be able to proceed with whatever you are doing, even if the object isnt found?
This is where inline rescue’s can help.
Now you can pull all of your finds together and end them with a rescue.
Example: Let’s say you had the following code:@person = Person.find(params[:id]) @employee = Employee.find(params[:employee_id])
Now, if either of these finds fail, you will get an error. Instead of rescuing the entire method, you can resuce each statement and make the return value nil and check for nil like you normally would.
@person = Person.find(params[:id]) rescue nil @employee = Employee.find(params[:employee_id]) rescue nil
Now when you cant find the ID, it will rescue and just set the variables to nil and move on.
You can also set the rescues to another default datatype instead of nil.
Now, you may be saying, “Wait, why would a user need to enter an id”. Well, one example is an order id, or a tracking number. Anyway, I have run across this a couple of times and thought i’d write something about it.
until next time.
—jake
Flvorful has launched!
Just starting the blog with a quick note about what we do. Basically, we deliver commercials into flash videos. Not just pre-roll, but also in the video. We connect the advertiser to the publisher through our online marketplace and some fancy algorithms :)
We will be putting up some examples of it soon. In the mean time you can check out how it works.
—jake
Rails Plugin - Jake's Rails Toolbox
hello all,
Ive recreated my old plugin and updated with some new features.
I created this plugin as a hodgepodge of different methods/hacks that i have found useful over the course of developing Rails Apps. I packaged it up as one plugin because most of the methods have nothing to do with each other, but i find them are very useful going from project to project.
Lets talk about them:
ActiveRecord Hacks:
1. Dynamic “nice_date”
Basically, i got tired of typing object.created_at.strftime(“%m-%d-%Y”) so i came up with the following method_missing hack for any Time attribute in an ActiveRecord object. Just prepend “nice_” in front of any Datetime attribute and you will get a nicely formatted date string. Plus some other goodies :)
Examples:
object.created_at # => Mon Dec 04 12:36:55 CST 2006 object.nice_created_at # => "12-04-2006" (mm-dd-YYYY) object.nice_created_at(:euro) # => "04-12-2006" (dd-mm-YYYY) plus, for you guys (and gals) that like using slashes instead of dashes: object.nice_created_at(:slash) # => "12/04/2006" (mm/dd/YYYY) object.nice_created_at(:euro_slash) # => "04/12/2006" (dd/mm/YYYY) and finally: object.nice_created_at(:rss) # => "Mon, 04 Dec 2006 12:36:55 -0600" (rfc822)
NOTE The attribute must be an instance of Time or a NoMethodError will be thrown
2. Dynamic SEO formatting.
Any method that returns a string can use this dynamic method. This method will create an SEO friendly string out of the attribute chosen (for use mainly in URLS). It will append the objects id (not the object_id, but the id key from the database) so that you can use params[:id] and not have to create new routes.
Example:
puts object.id # => 1 object.title = " Rails is freaking awesome, didn't you know that? " puts object.seo_title # => "1-rails-is-freaking-awesome-didnt-you-know-that"
3. nice_name
This one is pretty simple. I found myself adding this same method to alot of my applications. Basically it looks for an attribute called “first_name” and one called “last_name” and combines them together with a space in between.
Example:
object.first_name = "jake" object.last_name = "varghese" object.nice_name # => "jake varghese"
NOTE If the method doesn’t have EITHER first_name or last_name, then a NoMethodError will be thrown. It must have both attributes
4. create/new from XML
Create an ActiveRecord Object from XML. This method relies on the basics of AR’s current to_xml method (basically, it must be formatted the same).The differences between new_from_xml and create_from_xml are the same as the differences between AR.new and AR.create
If your XML string contains multiple records, it will parse out each record and create an object. The “multiple record” call returns an array like find(:all)
Example:
person = Person.new_from_xml(xml_string)
# => #<Project:0x2430758 @attributes={"prototype_url"=>nil, "company"=>"some value",
"order_id"=>45564, "phone_number"=>555544455, "created_at"=>nil,
"email_address"=>lkjlkjL@jfgg.com}, @new_record=true>
String Hacks:
1. SEO friendly.
This method is used in the AR seo hack. It takes a string and makes it seo friendly.
Example:
c.title = " Rails is freaking awesome, didn't you know that? " c.title.seo_friendly # => "rails-is-freaking-awesome-didnt-you-know-that"
Float Hacks:
1. to_s override.
I really hate using sprintf, mainly because i always have to go online and look up the syntax. I figured i make that a little easier. Now you can print floats with different precision as easily as:
Example4.123456.to_s(1) # => "4.1" 4.123456.to_s(3) # => "4.12" 4.123456.to_s(3) # => "4.123" 4.123456.to_s(4) # => "4.1235" (Note the auto rounding from 4.123456) 4.123456.to_s # => "4.123456"
Hash Hacks:
1. Method Missing hack to allow for easy hash referencing.
I can never remember whether the Hash i am playing with has symbols for keys or strings. I also dont like typing the brackets (not all text editors have the cool “auto close brace” feature). That’s why i came up with this method missing hack. Instead of explaining what it does, I’ll just show you.Example:
hsh = {"project"=>
{
"prototype_url"=>nil,
"designer_id"=>2,
"finished_at"=>nil,
"phone_number"=>"512225555",
"website"=>"http://www.ggg.com",
"first_name"=>"test"
}
}
hsh.project
#=> {"prototype_url"=>nil, "designer_id"=>2, "finished_at"=>nil,
"phone_number"=>"512225555", "website"=>"http://www.ggg.com",
"first_name"=>"test"}
hsh.project.prototype_url
#=> nil
hsh.project.designer_id
#=> 2
hsh.project.first_name
#=> test
So instead of hsh[“project”] you can just write hsh.project
and that’s it. If you want to try it yourself, just run
script/plugin install http://jakes-rails-toolbox.googlecode.com/svn/trunk/jakes_toolbox
You can also checkout the latest rev via SVN at:
svn checkout http://jakes-rails-toolbox.googlecode.com/svn/trunk/ vendor/plugins
New Rails Plugin - Acts As Noteable
So I was at work and I needed to add notes to multiple models in the same project (before i only had to worry about one model with notes, so it was pretty straightforward). So i bit down and knocked out this little plugin.
I borrowed heavily from Acts As Rateable by Juixe
Installation
Run the following command:
script/plugin install http://acts-as-noteable.googlecode.com/svn/trunk/acts_as_noteable
The install will try and copy some scripts over, this works sometimes. If you get a rake error do the following:
- cd vendor/plugins/acts_as_noteable
- rake update_scripts
Create a new rails migration:
script/generate migration add_notes_to_project
and add the following self.up and self.down methods
def self.up
create_table "notes", :force => true do |t|
t.column "from", :string, :limit => 50, :default => ""
t.column "body", :text, :default => ""
t.column "created_at", :datetime, :null => false
t.column "noteable_id", :integer, :default => 0, :null => false
t.column "noteable_type", :string, :limit => 15, :default => "", :null => false
end
end
def self.down
drop_table :notes
end
(one day i’ll add a migration script to the plugin to automatically add this :) )
After that run “rake migrate” to create the table.
Now all you need to do is call acts_as_noteable in your model:
class Model < ActiveRecord::Base acts_as_noteable end
Now your model is notable, but that’s not all.
For only 19.95 you get a Helper method to help you create a nice form. Ok, so i am not actually charging, but whatever.
Here’s how the helper works.
In the view you want to display notes in put the following:
<%= display_notes(object) %>
This will create a div filled with the note entries for the object and a AJAX form to add new notes to the object as well as delete notes from the object. The add and delete methods are stored in the notes_controller.rb that gets copied over into your app/controllers directory.
The full implementation for this method is:
<%= display_notes(obj, partial_name = "notes/note", controller_name = "notes") %>
I added the partial name and controller name in case you have multiple controllers in different folders, this way you can display notes for objects whose controllers are buried deep in a folder.
Example: I have an “admin” folder for all the backend stuff and I needed a way to reference the notes controller from different places, otherwise RAILS will assume you are trying to reference a controller from the current folder your in.
After you have called display_notes, your done.
Note** This plugin has not been tested with Rails 2.0 yet
peace
—jake