Posted by ant
January 9th, 2009
Filed in Rails, Sysadmin
Setup Phusion Passenger (mod_rails) Apache module
sudo gem install passenger- copy the snippet from the terminal and into a file called
/etc/apache2/other/passenger.conf - Restart Apache –
sudo apachectl restart
Install Passenger PreferencePane
This makes it really easy to create hosts for your Rails applications and configure mod_rails in System Preferences.- Download Passenger PreferencePane
- Double click to install, have a play in System Preferences.
Install Upload Progress Apache module
git clone http://github.com/drogus/apache-upload-progress-module.gitcd apache-upload-progress-modulesudo apxs -c -Wc,-arch -Wc,i386 -Wl,-arch -Wl,i386 -i -a mod_upload_progress.c- Change the architecture string (i386) if yours is different
- This installs and enables the module in
/etc/apache2/httpd.conf
/etc/apache2/passenger_pane_vhosts. To enable upload progress for a site edit the .conf file appropriate for your site and insert the below snippet just before the </VirtualHost> line.
<IfModule upload_progress_module>
<Location />
# enable the tracking of uploads anywhere down from /
TrackUploads On
</Location>
<Location /progress>
# progress JSON will appear at /progress
ReportUploads On
</Location>
</IfModule>
Reconfigure Passenger PreferencePane to insert upload_module configuration
The application I’m currently developing requires upload progress and Apache needs to be able to follow symbolic links as I have certain assets stored outside of the main Rails application. The default Passenger PreferencePane configuration does not include these options.
I’ve updated the file that creates this configuration in a forked github repository. Dependent on where you installed the PreferencePane this file will either be in
~/Library/PreferencePanes/Passenger.prefPane/Contents/Resources– Installed only for your user- or
/Library/PreferencePanes/Passenger.prefPane/Contents/Resources– Installed for all users
Download PassengerApplication.rb and copy this file and the above configuration will be created.
Thoughtbot Paperclip
Paperclip is a fantastic file attachment plugin. It just uses ImageMagick to do it’s image processing. As long as the executables are in your path image scaling just works. It’s a whole load easier than configuring RMagick.
However, none of my images were rescaling and were dumping a strange error saying that Paperclip couldn’t determine the type of my file. I spent an hour trying to work out what the problem was, then I realised… The ImageMagick commands weren’t in the path for Apache. I tried various things to get this working, but tracked it down to a setting that can be put in one of your environment files.
Paperclip.options[:command_path] = "/opt/local/bin"
A quick restart of Rails later and it’s all working. This is what Paperclip was chucking out to my the development log:
[paperclip] An error was received while processing: #<Paperclip::NotIdentifiedByImageMagickError: /tmp/stream.637.0 is not recognized by the 'identify' command.>
Posted by ant
October 24th, 2008
Filed in Rails, Sysadmin
sudo apt-get install imagemagick sudo apt-get install libmagick9-dev sudo gem install rmagick
Posted by ant
October 10th, 2008
Filed in Rails
The reason for my specific jaunts into the world of XSS protection were due to me wanting to implement a Rich Text Editor on the Rails project I’m currently working on. After considering numerous options (including FCKEditor, Yahoo YUI and Kupu) I decided to settle on TInyMCE for my editor of choice. It’s configurable, has a plugin architecture, it’s highly supported, has been around for ages etc etc..
Plus, I found a project called Tiny MCE Plus. It provides many of the helpers etc that makes it much easier to plug into Rails. It’s really easy to implement (and documented on the site) but what really interested me was the fact that there’s a TinyMCE plugin and Rails generator that does image uploads included!
I had to do a load of changes to this plugin to make it completely suit my needs, including refactoring the code to use jQuery rather than Prototype, but it was certainly something to use as a basis. The best Rails – Rich Text Editor combination I’ve found. I’ll be documenting my efforts more fully soon!
Posted by ant
October 9th, 2008
Filed in Rails
(or sanitising as us Brits prefer to write!)
I really hate having to call the hhelper method every time I display a model attribute in view. Imagine how happy I was to find a plugin that did all this for me. Then I found XSS_Terminate.
Attributes can be sanitiesd (have unwanted user inputted HTML tags removed) with one of three methods (remove all HTML tags, Rails’ own ActionView::Helpers::SanitizeHelper or HTML5Lib). By default all attributes in a model are sanitized using the remove all tags method, but you can easily configure the way attributes are sanitzed. For example to strip all tags from every attribute except :description use:
xss_terminate :sanitize => [:description]
Thankfully now Rails uses white rather than black lists for it’s sanitization (which it did prior to v2.0), which makes it much, much more effective. However, I found that using the Rails’ built in sanitization was removing attributes for html elements that (for the moment) I need left in. By default the methods will remove script, id, class and style attributes (amongst others). This can be configured in config/environment.rb (details in the API docs).
In the API document it says you can change allowed default attributes, what it means is
config.action_view.sanitized_allowed_attributes = 'class', 'style'
will add the ‘class’ and ‘style’ attributes to the list of allowed attributes and not change it to just ‘class’ and ‘style’.
Posted by ant
October 8th, 2008
Filed in Rails
I’m a huge fan of HAML, for me it just makes writing HTML markup ten times faster and it looks a shed load nicer too. With a new project I’m working on at the moment, I thought I’d give SASS (HAML for HTML, SASS for CSS). I’ve been using it for the past few weeks. Today I decided to change the SASS files in my Rails project back to plain old CSS. The reason for this?
- I like being able to put all the rules for one selector up on one line, it makes more sense to my brain.
- No colour coding in Textmate – It’s all white and I can’t see my arse from my elbow.
- I don’t really use the features that SASS offers, other than indenting code to form groups of rules, but I was already doing this with CSS anyway
It would be nice to still have the variables that SASS offers, I only used them for colours, but still nice. It’s just not worth the visual tradeoff though. Sorry SASS!
Posted by ant
October 7th, 2008
Filed in Rails, Sysadmin
.git/config .gitmodulesThese references need removing. The cached local copy can be removed with
git rm --cached path/to/submodule rm -r path/to/submoduleNote the lack of the trailing slash!
Posted by ant
October 1st, 2008
Filed in Rails, Sysadmin
I’ve been working with Git for my source control recently. It seems to work more appropriately for me than Subversion. This is primarily because you don’t have to be connected to the Internet to perform commits to the versioning system, it keeps the whole versioning database in a subdirectory called .git.
I did however, have some problems getting a remote repository setup stored on my Dreamhost account, but luckily I found some instructions on autopragmatic.com. Here I want to record the way to create a new repository
On your local machine
mkdir repo.git
cd repo.git
git init
touch .gitignore
git add .
git commit -m "added .gitignore"
# Down to here creates the local git repository and does first commit
git remote add origin ssh://user@example.com/home/user/git/repo.git
git config branch.master.remote origin
git config branch.master.merge refs/heads/master
# Configure the Git repository
git push --all
# push the changes to the remote Git repository.
Posted by ant
April 29th, 2008
Filed in Rails
I’ve been working on a project recently that’s needed me to generate human readable (and Google readable) permalinks to pages. As a default these permalinks are generated from the title of the associated object. This was all working until I realised that I had words like ‘café’ in the title. Using my existing algorithm any letters other than A-Z, a-z were removed, thus turning ‘café’ into ‘caf’. Not very human or Google readable.
I found an excellent article on Obie Fernandez’s blog showing how he tackled this problem for a job he was working on and all is now wonderful again!!!
Posted by ant
April 4th, 2008
Filed in Rails, Sysadmin
A really easy way of beta testing your Ruby on Rails application is to use Basic HTTP Authentication. There are methods built into Rails to do this in your application controller just put
before_filter :http_authenticate
def http_authenticate
authenticate_or_request_with_http_basic do |username, password|
username == 'my_username' && password == 'my_password'
end
end
Every request will put through this filter and users will not be able to use your site without this username and password.
Posted by ant
April 4th, 2008
Filed in Rails, Sysadmin
I’m currently working on an app that we’re going to be deploying on Brightbox. However, I ran into a couple of problems when deploying with their gem.
First, my app’s Subversion repository isn’t on the Brightbox server. This was simple, in the config/deploy.rb file, change the address of the repository to the address of the server. Create a SSH key on the Brightbox box (mouthful!) and add the public key to the .ssh/authorized_keys on my Subversion server and away we go!
config/database.yml in the svn repository. The reasons for this are
# Security – if someone checks out my code they end up knowing my passwords.
# there are several people working on the project so every time a commit/update was performed, it would reset your config/database.yml file to whatever the last checked in version was, annoying.
In the config/deploy.rb file I added:
task :after_update_code do
run( "cp $HOME/database.yml #{release_path}/config/")
end
to the config file and put the database.yml file in my home directory. Now, after the code’s been checked out the database.yml file is copied into the correct place. Hurrah!
The third thing was really my fault. I’d put a - in my database name. The Brightbox gem doesn’t escape the CREATE DATABASE database_name database name (it should really be CREATE DATABASE `database_name`). MySQL was interpreting my - as subtraction, oops. I changed the name of the database to only use underscores and it worked fine.
setup task. This sets up the shared directory in your application deployment and will not run without it. I added
task :before_cold_deploy do
setup
end
to config/deploy.rb to run the Capistrano setup task.
Then… HURRRAH! It works!!!
Posted by ant
October 18th, 2007
Filed in Rails
Update – This has now been fixed and included in Release 3007 Hurrah!!!!
I’ve found a bug in Rick Olsons attachment_fu plugin. If you create image attachments and using a different model for the thumbnails, eg.
class Image < ActiveRecord::Base has_many :thumbnails, :dependent => :destroy has_attachment :content_type => :image, :thumbnail_class => ‘Thumbnail’, :thumbnails => { :sidebar => “x200” }, :storage => :file_system validates_as_attachment end
class Thumbnail < ActiveRecord::Base belongs_to :image has_attachment :content_type => :image, :storage => :file_system end
If you have an image with an id of 1 and a thumbnail with an id of 1 then when you try to destroy image (id=1) the code will go into an infinite loop as the destroy_thumbnails function will think the thumbnail itself is has thumbnais and try to recursively delete itself until the stack level gets too deep.
def thumbnailable?
image? && respond_to?(:parent_id)
end
def destroy_thumbnails
self.thumbnails.each { |thumbnail| thumbnail.destroy } if thumbnailable?
end
To make sure only the base image is considered to have thumbnails. The thumbnailable? function can be changed to:-
def thumbnailable?
image? && respond_to?(:parent_id) && parent_id.nil?
end
The attached patch updates this and implements a test to ensure it works.
Posted by ant
October 18th, 2007
Filed in Rails
I’ve been doing quite a lot of Behaviour Driven Development using RSpec recently. However, I hit a problem topday, I was trying to test file uploads to Rick Olson’s attachment_fu plugin. First I thought all I had to do was to pass it a file handle or contents of a file, not so. The tests failed moaning of missing methods. I had a rummage around in the tests for the plugin itself.
A upload_file function is called in the attachment tests and defined in test/test_helper.rb. This in turn calls the Rails fixture_file_upload function. This creates a fake file upload which can then be used to create a new attachment.
The only thing is that all the files are uploaded to the public directory which leave it rather messy. In the code I’m using below told both the path_prefix for my attachment to be the tmp/test_images directory and deleted that after each test incarnation. The only problem with this is that it takes ages for the tests to run. :-(
TEST_DIR = "tmp/test_images"
before(:each) do
Image.attachment_options[:path_prefix] =
"#{TEST_DIR}/images"
@image = Image.create :uploaded_data =>
fixture_file_upload("test_image.jpg", "image/jpg")
end
after(:each) do
@image.destroy
FileUtils.rm_rf File.join(RAILS_ROOT, TEST_DIR)
end
Posted by ant
October 17th, 2007
Filed in Rails
I love HAML and SASS, they’re such beautiful ways of ways of writing HTML and CSS respectively. I saw Hampton do his (I believe first) presentation at RailsConf Europe 2006 in London last year with a can of Stella and no small amount of profanity! It was a fantastic presentation and I remember commending him on a good job whilst having a cigarette outside. I started using HAML pretty much immediately after that.
However, I’ve always been a bit annoyed that TextMate doesn’t have support for it. I’ve probably just not been keeping up, but I’ve now found that in the Macromates SVN repository there is a bundle that enables HAML support in TextMate, hurrah. The URL for this bundle is http://macromates.com/svn/Bundles/trunk/Bundles/Ruby%20Haml.tmbundle
All you have to do is go to your ~/Library/Application Support/TextMate/Bundles directory and do a svn co http://macromates.com/svn/Bundles/trunk/Bundles/Ruby%20Haml.tmbundle and the support will be in TextMate. Well done Macromates and the guys at Unspace.
Posted by ant
August 14th, 2007
Filed in Rails
I’ve just been getting autotest (part of the ZenTest suite) to work. It’s a really good framework for just getting your tests to run automatically in the background.
Following the instructions in one of the fantastic PeepCode screencasts I got the notifications from autotest to get piped though to Growl
In the PeepCode Episode there’s a link to to Wincent Colaiuta’s knowledge base on how to do this. However, it would seem that the formatting of the RSpec output has changed since this ~/.autotest file was written. “Not implemented” strings have changed to “Pending”
49 examples, 0 failures, 1 pending
I’ve rewritten the file and you can find it below. I also extended it slightly as I wanted to see when tests were pending. Now if there are no failures, but there are pending descriptions they will be flagged up with a different icon so you know theres some tests to be implemented.
require 'autotest/redgreen'
module Autotest::Growl
def self.growl title, msg, img, pri=0, stick=""
system "growlnotify -n autotest --image #{img} -p #{pri} -m #{ msg.inspect} #{title} #{stick}"
end
Autotest.add_hook :ran_command do |autotest|
results = [autotest.results].flatten.join("\n")
output = results.slice(/(\d+)\s+examples?,\s*(\d+)\s+failures?(,\s*(\d+)\s+pending)?/)
if output =~ /[1-9]\sfailures?/
growl "FAIL:", "#{output}", "~/Library/autotest/rails_fail.png", 2, "-s"
elsif output =~ /[1-9]\spending?/
growl "PENDING:", "#{output}", "~/Library/autotest/rails_pending.png", 2, "-s"
else
growl "PASS:", "#{output}", "~/Library/autotest/rails_ok.png"
end
end
end
Posted by ant
August 8th, 2007
Filed in Rails
I submitted my first patch to Rails yesterday. I found that if you render a partial with a layout before you call yield in your site layout, the value that is returned by yield is whatever was rendered by your partial (without it’s layout) and not the rendered action as expected.
This is because the requested action is rendered before it’s layout, then stored in @content_for_layout (in the ActionView object). When render :partial => ‘blah’, :layout => ‘my_layout’ is called it stores it’s value in, you guessed it, @content_for_layout, thus overwriting the rendered action with the rendered partial. Thus, when you call yield from your site layout, the last partial rendered with layout (just the partial bit though) will always be returned.
The patch creates a copy of the current @content_for_layout before doing a render, then sets it back to its original value once the render has completed. It doesn’t seem to appear on the main ticket listing page though, I’m not sure why.
Blog uses Mephisto
Design from OSWD
by dreamLogic
