<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Company Blog &#187; how-to</title>
	<atom:link href="http://edendevelopment.co.uk/blogs/company/category/how-to/feed/" rel="self" type="application/rss+xml" />
	<link>http://edendevelopment.co.uk/blogs/company</link>
	<description>Eden Development Company Blog</description>
	<lastBuildDate>Sun, 21 Feb 2010 08:22:31 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.6</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>redirect_to :back not reliable</title>
		<link>http://edendevelopment.co.uk/blogs/company/2009/04/02/redirect_to-back-not-reliable/</link>
		<comments>http://edendevelopment.co.uk/blogs/company/2009/04/02/redirect_to-back-not-reliable/#comments</comments>
		<pubDate>Thu, 02 Apr 2009 09:09:50 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[code]]></category>
		<category><![CDATA[how-to]]></category>
		<category><![CDATA[under the hood]]></category>

		<guid isPermaLink="false">http://edendevelopment.co.uk/blogs/company/?p=401</guid>
		<description><![CDATA[Suppose you want to allow someone to make a comment and then return to the page they were on. An easy way to do this in Rails is to set the CommentsController method to redirect_to :back

def create
  comment = Comment.new(params[:comment])
  if comment.save
    redirect_to :back
  end
end

But beware! The trouble with [...]]]></description>
			<content:encoded><![CDATA[<p>Suppose you want to allow someone to make a comment and then return to the page they were on. An easy way to do this in Rails is to set the CommentsController method to redirect_to :back</p>
<pre lang='ruby'>
def create
  comment = Comment.new(params[:comment])
  if comment.save
    redirect_to :back
  end
end
</pre>
<p>But beware! The trouble with this is that Firefox has an option to disable referrers, so you can&#8217;t rely upon the HTTP_REFERER being set.</p>
<p>So you could set up a session variable when you display your comment form, to later be used in the controller. The current url is found in request.path</p>
<pre lang='ruby'>
<% session[:return_to] = request.path -%>
</pre>
<pre lang='ruby'>
def create
  comment = Comment.new(params[:comment])
  if comment.save
    redirect_to session[:return_to]
  end
end
</pre>
<p>Sure, people can turn off session cookies, but if they do that then you have all sorts of other Rails problems to do with authenticity tokens and user authentication, so I think this is a fairly safe method.</p>
<p>Of course, an even better option is to add the comment by AJAX and avoid the need for a page refresh at all &#8230; but that can be the topic of a different blog post!</p>
]]></content:encoded>
			<wfw:commentRss>http://edendevelopment.co.uk/blogs/company/2009/04/02/redirect_to-back-not-reliable/feed/</wfw:commentRss>
		<slash:comments>15</slash:comments>
		</item>
		<item>
		<title>Under the hood: Not-so-basic authentication</title>
		<link>http://edendevelopment.co.uk/blogs/company/2009/03/23/under-the-hood-not-so-basic-authentication/</link>
		<comments>http://edendevelopment.co.uk/blogs/company/2009/03/23/under-the-hood-not-so-basic-authentication/#comments</comments>
		<pubDate>Mon, 23 Mar 2009 07:19:28 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[code]]></category>
		<category><![CDATA[how-to]]></category>
		<category><![CDATA[under the hood]]></category>

		<guid isPermaLink="false">http://edendevelopment.co.uk/blogs/company/?p=396</guid>
		<description><![CDATA[Recently I worked on a project that required a single login to access administration options. There was no need for a full-blown RESTful authentication solution &#8211; I was advised to &#8220;Just use basic auth!&#8221;
Rails makes it easy. You probably know the standard example. You put a before_filter :authenticate in the controllers that require it, and [...]]]></description>
			<content:encoded><![CDATA[<p>Recently I worked on a project that required a single login to access administration options. There was no need for a full-blown RESTful authentication solution &#8211; I was advised to &#8220;Just use basic auth!&#8221;</p>
<p>Rails makes it easy. You probably know the standard example. You put a <code>before_filter :authenticate</code> in the controllers that require it, and set it up in the Application Controller.</p>
<pre lang='ruby'>
def authenticate
  authenticate_or_request_with_http_basic do |user, password|
    user == 'admin' &#038;&#038; password == 'pass'
  end
end
</pre>
<p>It&#8217;s all well and good &#8230; until you want to add a log out button. The browser stores the successful login credentials in a sort of cookie, and applies them to every page which requests basic authentication. Once you&#8217;ve logged in, it&#8217;s actually quite hard to make the browser forget you until you quit and restart the browser. It&#8217;s hard, but not impossible. If you can force basic authentication to fail, the browser will throw away the credentials.</p>
<p>So the solution is to add a session variable that says &#8220;NO SRSLY, LOG ME OUT PLS!&#8221; This is the logout action (a destroy method in a Sessions Controller)</p>
<pre lang='ruby'>
def destroy
  session[:logout_requested] = true
  flash[:notice] = "You have logged out successfully"
  redirect_to(root_path)
end
</pre>
<p>Now for the tricky bit. The way this works is subtle and takes a moment to figure out each time I think about it. We change the authenticate method in the Application Controller so that as well as checking the username and password, it also ensures that this flag has not been set. Meaning we can cause basic authentication to fail when we want it to.</p>
<pre lang='ruby'>
def authenticate
  authenticate_or_request_with_http_basic do |user, password|
    user == 'admin' &#038;&#038; password == 'pass' &#038;&#038; session[:logout_requested] != true
  end
  session[:logout_requested] = nil
end
</pre>
<p>Next time our user goes to a page which requires authentication, the browser still provides the correct username and password, but the flag causes the basic authentication to fail. Obviously we then have to clear the flag straight away, otherwise the user would not be able to get back in again even with the correct credentials. The user must type in the correct login name and password again to be able to get back in.</p>
<p>Perhaps we want to know whether the user is logged in or not, so that we know whether to display an edit button. We can set another session variable. Conveniently, <code>authenticate_or_request_with_http_basic</code> returns a boolean value.</p>
<pre lang='ruby'>
def authenticate
  session[:logged_in] = authenticate_or_request_with_http_basic do |user, password|
    user == 'admin' &#038;&#038; password == 'pass' &#038;&#038; session[:logout_requested] != true
  end
  session[:logout_requested] = nil
end
</pre>
<p>Remember to set the flag to false when you log out. Also remember that this flag could be true, false or nil so a check in the Application Controller looks like this:</p>
<pre lang='ruby'>
def logged_in?
  session[:logged_in] == true
end
</pre>
<p>Finally it&#8217;s worth noting that the username and password do not have to be hard-coded like this. It&#8217;s simple for an example, but don&#8217;t think that&#8217;s all there is to basic authentication. There&#8217;s nothing to stop you comparing against values in a settings table or even doing a user lookup à la RESTful authentication.</p>
<pre lang='ruby'>
def authenticate
  session[:logged_in] = authenticate_or_request_with_http_basic do |email, password|
    user = User.authenticate(email, password)
    if user &#038;&#038; session[:logout_requested] != true
      self.current_user = user
      true
    else
      self.current_user = nil
      false
    end
  end
  session[:logout_requested] = nil
end
</pre>
<p>Thanks to Richard and Tris for their help in figuring out the not-so-basic aspects of basic authentication! :)</p>
]]></content:encoded>
			<wfw:commentRss>http://edendevelopment.co.uk/blogs/company/2009/03/23/under-the-hood-not-so-basic-authentication/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Twitter integration from your Rails app</title>
		<link>http://edendevelopment.co.uk/blogs/company/2009/02/26/twitter-integration-from-your-rails-app/</link>
		<comments>http://edendevelopment.co.uk/blogs/company/2009/02/26/twitter-integration-from-your-rails-app/#comments</comments>
		<pubDate>Thu, 26 Feb 2009 13:17:39 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[code]]></category>
		<category><![CDATA[how-to]]></category>
		<category><![CDATA[twitter]]></category>
		<category><![CDATA[ykyat]]></category>

		<guid isPermaLink="false">http://edendevelopment.co.uk/blogs/company/?p=347</guid>
		<description><![CDATA[We&#8217;ve learnt a bit about Twitter from writing ykyat.com.
I particularly want to write about how we fetch Twitter user icons. The icons are stored on AWS (Amazon Web Services) and cannot be deduced from the user name. You have to go through the Twitter API to find the image location.
The first thing I tried was [...]]]></description>
			<content:encoded><![CDATA[<p>We&#8217;ve learnt a bit about Twitter from writing <a href="http://ykyat.com">ykyat.com</a>.</p>
<p>I particularly want to write about how we fetch Twitter user icons. The icons are stored on AWS (Amazon Web Services) and cannot be deduced from the user name. You have to go through the Twitter API to find the image location.</p>
<p>The first thing I tried was the <a href="http://twitter4r.rubyforge.org/">Twitter4R</a> library. This seems to be a very powerful library, and if you were writing a full Twitter client in Ruby you&#8217;d definitely want to consider it. It was simple to get the user icons, but the library just felt a little over-the-top for our needs.</p>
<p>Twitter4R seemed to require authentication with every request, and we soon hit the API limit. I realised this is odd because you really don&#8217;t need to authenticate to look at the XML or JSON data about a Twitter user. I decided to go back to basics and do it myself. This is the code for parsing the JSON data and picking up the user icon URL:</p>
<pre lang='ruby'>
def icon_url_for_user(username)
  require 'open-uri'
  require 'json'
  buffer = open("http://twitter.com/users/show/#{username}.json").read
  result = JSON.parse(buffer)
  result['profile_image_url']
end
</pre>
<p>See! Easy!</p>
<p>Most people don&#8217;t change their user icon very often, so once we know where to find a user&#8217;s icon, we don&#8217;t need to ask Twitter for it again for an arbitrary amount of time. A week seems quite sensible. To that end, we created a lookup table in our database to match Twitter user names to their user icon URL. We added an index to the user name column because it acts as the primary key lookup.</p>
<p>When we want to know a user&#8217;s icon, we first look up in our table. If we don&#8217;t yet have it, or if the <code>updated_at</code> date is more than a week ago, we check with Twitter for the image location. Otherwise we use our cached location.</p>
<p>Fast and easy! :)</p>
]]></content:encoded>
			<wfw:commentRss>http://edendevelopment.co.uk/blogs/company/2009/02/26/twitter-integration-from-your-rails-app/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>Exporting from Rails to Excel</title>
		<link>http://edendevelopment.co.uk/blogs/company/2009/02/03/exporting-from-rails-to-excel/</link>
		<comments>http://edendevelopment.co.uk/blogs/company/2009/02/03/exporting-from-rails-to-excel/#comments</comments>
		<pubDate>Tue, 03 Feb 2009 13:57:19 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[code]]></category>
		<category><![CDATA[how-to]]></category>

		<guid isPermaLink="false">http://edendevelopment.co.uk/blogs/company/?p=266</guid>
		<description><![CDATA[There are various methods for exporting data from Rails to an Excel spreadsheet, some more complicated than others.
One easy way we&#8217;ve used a few times is to make use of Excel&#8217;s ability to interpret HTML tables as spreadsheet rows and columns. For example, i can set up a helper method to turn a collection of [...]]]></description>
			<content:encoded><![CDATA[<p>There are various methods for exporting data from Rails to an Excel spreadsheet, some more complicated than others.</p>
<p>One easy way we&#8217;ve used a few times is to make use of Excel&#8217;s ability to interpret HTML tables as spreadsheet rows and columns. For example, i can set up a helper method to turn a collection of tasks into a table in a simple HTML page:</p>
<pre lang='ruby'>module TasksHelper
  include ActiveSupport::Inflector

  def generate_xls(tasks)
    output_columns = [:title, :due_date]

    returning String.new do |str|
      str << "<html><head></head><body>
<table border='1'>"
      str << "
<tr>"
      output_columns.each do |col|
        str << "
<th>#{humanize(col)}</th>

"
      end
      str << "</tr>

"

      tasks.each do |task|
        str << "
<tr>"
          output_columns.each do |col|
            str << "
<td>#{task.send(col)}</td>

"
          end
        str << "</tr>

"
      end
      str << "</table>

</body></html>"
    end
  end

end</pre>
<p>The <code>environment.rb</code> file is going to have to know about the .xls extension:</p>
<pre lang='ruby'>Mime::Type.register "application/vnd.ms-excel", :xls</pre>
<p>The <code>TasksController</code> can now be taught to respond to .xls and <code>send_data</code> as a file for download:</p>
<pre lang='ruby'>class TasksController < ApplicationController
  include TasksHelper

  def index
    @tasks = Task.find(:all)

    respond_to do |format|
      format.html # index.html.erb
      format.xls {
        send_data(generate_xls(@tasks),
          :filename => 'all_tasks.xls',
          :type => 'application/vnd.ms-excel')
      }
    end
  end

end</pre>
<p>When visiting <a href="http://localhost:3000/tasks.xls">/tasks.xls</a> we will now be given the option to download <code>all_tasks.xls</code> which Excel will parse quite happily as a spreadsheet.</p>
<p>One important consideration: Excel is not overly fond of Unicode, and Rails by default will send data in UTF-8 format. If the data contains Unicode characters such as curly quotation marks, you will get some weird output like <code>â€œ</code> in the spreadsheet.</p>
<p>Not to worry! We can use Ruby&#8217;s implementation of the <a href="http://en.wikipedia.org/wiki/Iconv">iconv</a> API to convert to Excel&#8217;s preferred format, ISO-8859-15.</p>
<pre lang='ruby'>class TasksController < ApplicationController
  include TasksHelper

  def index
    @tasks = Task.find(:all)

    respond_to do |format|
      format.html # index.html.erb
      format.xls {
        require 'iconv'
        converter = Iconv.new('ISO-8859-15//IGNORE//TRANSLIT','UTF-8')
        send_data(converter.iconv(generate_xls(@tasks)),
          :filename => 'all_tasks.xls',
          :type => 'application/vnd.ms-excel')
      }
    end
  end

end</pre>
<p>The Unicode curly quotes are transformed into standard quotes, and Excel is happy again!</p>
<p>Acknowledgements and references:</p>
<p><a href="http://wiki.rubyonrails.org/rails/pages/HowtoExportDataAsCSV">How to export data as CSV</a><br />
<a href="http://www.peterkrantz.com/2007/utf8-in-pdf-writer/">Working with UTF-8 in PDF::Writer and Ruby on Rails</a><br />
<a href="http://www.ruby-doc.org/core/classes/Iconv.html">Iconv Ruby class</a></p>
]]></content:encoded>
			<wfw:commentRss>http://edendevelopment.co.uk/blogs/company/2009/02/03/exporting-from-rails-to-excel/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
	</channel>
</rss>
