The game just completely changed

Something insane is happening in the creative industry and all of you need to know about it. Two recent events have completely changed the career prospects for Web Designers and Developers: 1) Frank Chimero's Kickstarter project and 2) Natasha Wescoat's live painting sessions.

Let me explain ...

 

Frank’s Story …

Frank Chimero is a talented designer who thought “You know, it’d be awesome to write a book.”

Photo of Frank with a painting of a city behind him

Instead of going the traditional publishing route, he decided to ask for funding to write the book before he’d even started. He used a site called Kickstarter which allows people to ‘back’ projects by pledging money and if the goal is hit, then the money is paid out and the project begins. He announced the project with this tweet:

Announcing The Shape of Design, the book. Back me on Kickstarter? kickstarter.com/projects/30453…

He decided to set the goal at $27,000 and insanely, he crushed that goal in less than a day, and now, two days later he’s up to $51,000. I’m not sure how he came up with the $27K figure, but I assume he added up the costs for his time, the printing and shipping.

Let me share one more interesting project, before I share my conclusions …

Natasha’s Story …

Natasha Wescoat is a very talented painter.

One of Natasha's painting that's a tree with bright circles for leaves and an orange sky

Natasha paints live on uStream and Justin.tv. As she works on a piece, viewers watch and by the end, there is often a bidding.

Here she is starting the painting …

Ustream video of Natasha starting a painting.

and then finishing it about 3 hours later …

Ustream video of Natasha finishing a painting.

What’s the huge shift?

The power of crowd-funding sites like Kickstarter, and the entertainment draw of Ustream have created a brand new channel for designers (and developers, which I’ll cover in a minute) to get paid for doing something they love.

This model allows anyone with talent and a decent following (Twitter, Blog, Facebook, etc) to leave freelance and client work behind. They can simply move from  project to project, knowing that it will be a success before they even start, while also determining the subject matter of the work.

It’s similar to the patronage model, but you get to pick the creation. Wild.

Natasha has learned to combine her talent (painting) with live entertainment. There’s something very intriguing about watching someone live-paint, knowing you might be able to purchase the work at the end.

So how can you take part in this revolution?

  1. Put in a good 2-3 years of hard work, building your following on Twitter, Facebook and your blog. Frank has around 13,000 Twitter followers, which is a decent chunk, but isn’t impossible to attain. You can’t expect to just click your fingers and succeed like this. Gotta do the time.
  2. Be damn good at what you do. You’ll need to build a reputation and being kick ass and creative. Obviously no one is going to want to fund you if your work is sub-par.
  3. Have an idea that’s creative, original and valuable. Just because you’ve achieved #1 and #2 above doesn’t mean any project your throw up on Kickstarter will succeed. The project has to stand on its own two feet.

What about Developers?

I also believe there’s an exciting opportunity for Developers here as well. Imagine this scenario …

You spot a much needed tool or service. A new framework, iPhone app, plug-in, etc. You decide you can create an awesome solution and you can dedicate a couple months to building something awesome. You create the project on Kickstarter and everyone who funds you gets a copy of the app/software/etc and a few exclusive goodies.

I’m hugely excited by this new model and it’ll be interesting to see what other projects crop up.

I can’t help thinking that two folks who should’ve done this are Ethan Marcotte (a book on Responsive Design) and Elliot Jay Stocks (with 8faces). I know Ethan is publishing a RD book with A Book Apart soon, but he could’ve completely controlled the project on his own if he wished. Getting published by a respected source like Zeldman and Co is awesome but it would’ve been interesting to see him, Cederholm or Keith do their books via Kickstarter instead.

Love to hear your thoughts!

Source : http://thinkvitamin.com/design/the-game-just-completely-changed/

5 Fabulous Friday Links for Web Developers

It’s Friday again. Where did the last 5 days go? Since many of you are starting a long weekend, you probably won’t appreciate a long, complex tutorial. Therefore, here are a number of useful links I’ve discovered recently which could ease your development burden when you return next week…

CopyPasteCharacter.com
copypastecharacter.com

If you don’t know your &raquo’s from your &rdquo’s, copypastecharacter.com is a great tool which could help you find the right HTML entity. Click any symbol and its character or HTML code is copied to the clipboard.

If you require something a little more sophisticated, the XHTML Character Entity Reference provides a categorized list of characters with their HTML entity code, numerical reference and unicode representation (useful for JavaScript).

ge.tt
Easy File Sharing with Ge.tt

Do your clients often try to send you videos or other large files from their AOL email account? Save their sanity and suggest they use Ge.tt.

While there are many file sharing systems, Ge.tt is one of the easiest I’ve seen. It’s free, there’s no need to register and there are no file size limits. File links can be sent to others via email, Twitter or Facebook. Your data is retained for 90 days, you can access download statistics and the developers are creating an API.

supportdetails.com
Support Details

It’s Friday, 5.30pm and your phone rings. It’s ClientX and they’re not happy. “My site doesn’t work.” they claim, “It’s broken and I want it fixed now”. You load the URL and everything seems fine.

A long conversation follows as you try to identify the problem. Unfortunately, the client doesn’t know what browser they’re using — they don’t know what a browser is. It’s futile to ask about their OS, screen resolution, color depth, version of Flash, or JavaScript state.

Fortunately, supportdetails.com can answer many questions for you. Ask them to visit the site and enter your email address to receive a report about their system. They’re probably running IE3.0 on their Great Aunt’s Windows 3.1 PC.

8bitalpha.com
Convert PNGs with 8bitalpha.com

24-bit alpha-transparent PNGs are great. However, Fireworks users know that 8-bit PNGs are smaller and work in more browsers. If you don’t use Fireworks, 8bitalpha.com may help. Simply drag your 24-bit masterpiece into the page and have an optimized 8-bit version returned.

ninite.com
Install and Update Software with ninite.com

Have you recently received a new PC? How long did it take to download and install your vital software, developer tools, browsers, media players, runtimes, virus checkers and utilities? How long does it take to find, download and install updates?

Save those lost hours with ninite.com. It’s easy: choose your applications, download the installer, and let it do the hard work for you. The installer can be run again when you want to check for updates.

ninite.com is primarily for Windows users who don’t have the luxury of a built-in package manager. That said, a Linux version of ninite.com is also available.

Bonus Link: URL Hunter

Are you fed up with fancy 3D games? URL Hunter is possibly the simplest browser-based game ever devised. It’s played in the URL bar and your task is to shoot the ‘a’ characters. It’s hardly Call of Duty, but it’ll give you a few moments pleasure and no one will realize you’re enjoying yourself.

Have a great weekend!

Source : http://www.sitepoint.com/5-fabulous-links-web-developers/

8 Reasons I love Ruby

In the last year I abandoned .NET for Ruby in my side projects and actual job.  In the interest of not explaining my rationale over and over again, I'm going to talk here about why I love Ruby so passionately.

Ruby is vastly more productive than Java or .NET.

I had heard that Ruby was more productive for years. Each time I rolled my eyes, confident these developers lacked my Resharper/Automocking/Generics/Fluent API Magic.  Then l developed in Rails at GiveCamp last year and holy dear god I was nearly as productive in this framework I barely knew as I was in ASP.NET MVC, a platform I knew inside out.  What the hell was I doing with my life? 

I am not an outlier in feeling this way.  Never in the history of man has a software developer said "I'm stuck doing Ruby for my day job but I'm really hoping to find a job in .NET or Java."

Thoughtworks, a company I'm pretty sure only employs geniuses, conducted a survey on the productivity of their Ruby projects.  Out of 30 projects surveyed, 80% reported being at least 50% more productive because they used Ruby instead of Java or .NET with more than 60% claiming a productivity increase of 2x or greater. (Only one project (3.3% of projects) reported actually being slower for using Ruby, while 90% of projects reported some increase in productivity.)

In my own estimation, I'd say Rails is somewhere between two and three times more productive than ASP.NET (MVC or Webforms).  That means I believe a 5 month .NET project could be done in 2 months in Ruby!

Why is Ruby so many times more productive than .NET or Java?

1) Gems

There have been rumblings about .NET's need for a package management system, but that is not what makes the gem ecosystem.

What makes Ruby Gems awesome is that, for various reasons, there are gems for everything!  So many problems are already solved!

Video of me whenever I run "gem install"

 

Some recent requirements I solved with a simple "gem install":

  • PDFs. gem install pdfkit, add two lines of code and bam, I can add .pdf to a route and get a pdf version.
  • Excel.  just setup the mime type with one line of code, call .to_xls on any collection and I get an excel doc returned!
  • Verb conjugation.  I need to figure out how to get the past perfect test of a verb.  "gem install verbs"
  • Here's a hard one:  I'd need profile pictures uploaded to amazon s3 and cropped to three different thumbnail sizes.  I also need to run asynchronously so my user doesn't wait 30 seconds after updating their profile.  And I should show a default picture of the appropiate size if they haven't uploaded one.  This would take how many days in .NET?  In Ruby I just had to gem install delayed_paperclip and just call one method in my model.  I had this working in minutes. 

Then there's twitter, devise, pickle, formtastic, friendly_id... 

2) Consistency

Ruby tools evolve naturally. Survival of the fittest. The best tools rise to the top; bad tools get ignored. There are different ORMs, view engines, etc, but they usually only exist when they solve a different need.  Ruby tools are crafted to fulfill actual needs and don't have to compete with tools dreamed up to be marketable.  There is no split in the Ruby community where half the developers use MSRake or MSSinatra.  Every single developer knows and uses Rake!

Because everyone knows Rake, ActiveRecord, Cucumber and RSpec, being a Rails Dev actually means something.  I have to be very skeptical when interviewing a ".NET developer" and figure out what kind of .NET dev they are. 

Every .NET project reinvents the wheel with deployment, ORMs, Migrations, project structure, while every Rails project is nearly identical. This might sound boring, but these inconsequential decisions are already made and free you to solve the actual business problem.  (This consistency is also what allows so many gems to integrate so seamlessly)  It also lets me be confident any experienced Rails Dev is a good fit for my project.  In fact, I hired someone on oDesk this month to help out on a Rails side project. I looked at his github, saw he knew his stuff and he was able to dive in with no ramp up time at all.  I would never dream of doing that in .NET.  

3) Git/Github

With DVCS and the ubiquitness of github, if I need to add functionality to a project, I just can!  I just fork, reference my fork in my GemFile (this lets my repository build my version of the gem instead of the one at rubygems.org) and issue a pull request to the project's owner.  Hopefully my change gets pulled into the main repo and I can go back to referencing the main gem.  It's not the end of the world if that doesn't happen, thanks to the beauty of git, I can keep pulling in new changes from the main repo.  The fact that this project will actually have automated tests lets me be comfortable that my patch did not break any functionality.  

On that note...

4) Testing

Testing isn't controversial in the Ruby community.  Projects without tests are seldom taken seriously.  On Codeplex, it's difficult to find a .NET project with unit tests.

Unit testing in a static language is much harder.  For example, you can not use the ActiveRecord pattern, because you would have no way to mock your database operations.  You have to wrap every single service in an interface and inject every depdenency.  That means wraping things that seem outright silly, like having a class and interface just to wrap DateTime.Now so you can stub it for your tests.  In Ruby, you can mock anything at any time.  (And for the usecase I just mentioned it's of course solved, simply gem install timecop.)

5) Ruby, The Language

Much is made of this, so I won't dwell here.  However the power, the beauty, expressiveness and openness of the language is what allows this community to thrive in the first place, so it definitely shouldn't be overlooked. 

6) Things just work

The Ruby community hates configuration and complexity.  When I install a gem, it usually Just Works.  

Ruby developers seek to ease the pain .NET developers don't even think about.  Ruby has made great progress in removing the pain of XML, CSS, JavaScript Includes, running unit testsmanaging dependencies, automating deployment and even JavaScript testing, 

7) Heroku

This fits in the Things that Just Work bullet, but no place on this planet can you set up a website in 30 seconds with three lines of code.  Then once you're set up, you can just click a checkbox to get email notifications of exceptions, or code analysis, or a MongoDB database or a bulk email service.  And deployment is just "git deploy heroku."  Oh yeah, and its all free until you start doing signficiant traffic.  I never dreamed of hosting so many websites so painlessly. 

8) Simplicity 

Have I mentioned that all these problems are solved and all this shit just works all the time?

I realized how far I had strayed from .NET when a .NET friend told me "Yeah, I got Azure set up in two hours."

I replied, "Ouch, I'm sorry."

"What? I thought that was pretty good."

Source : http://iggy.nu/8-reasons-i-love-ruby

10 Must Have Ruby Gems

One of the most beautiful things about Ruby development is the ease of adding functionality through packaged libraries called gems. With the power of Bundler, you can quickly add and manage gems in few lines of code. I'd like to share the 10 must-have gems which allow me to focus on what's unique to my app.

 

1. Devise (Authentication)

Just about every public-facing Rails app needs some type of authentication scheme. Authentication is often confused and interchanged with authorization, although the 2 terms have very distinct meanings.

In a nut shell, authentication determines if users are who they say they are, commonly through a username and password combination. Authorization determines which actions an authenticated user can perform. Devise is a solution to the former problem. I recently switched from AuthLogic in favor of Devise’s advanced engine for providing models, controllers and views. AuthLogic leaves it up to the developer to create the views and controllers. However, views are generally the first thing you should override, but thankfully Devise makes that easy as well.

Devise is a very active gem, and in conjunction with omniauth, has made it incredibly simple to setup Facebook and Twitter login buttons in less than a dozen lines of code. At first, the engine seemed too overbearing for me, but once I understood how easy it is to override and extend Devise, I made the switch.

https://github.com/plataformatec/devise

2. CanCan (Authorization)

CanCan is an incredibly easy way to define and access user permissions. All apps tend to have some sort of authorization scheme, but it’s generally setup adhoc, and leads to very messy view code. If you have dozens of if object.user == current_user statements littered among your views and controllers, it’s time to take a look at CanCan.

If you aren’t authorizing the current user to modify a provided object in update actions, a user could send a post request to update another user’s project, for example. With CanCan, your app’s authorization scheme is defined centrally in an Ability model. By using the can? method, you can check to see if the current user is authorized to perform an action to handle conditional view rendering.

CanCan also makes it dead simple to authorize controller actions and handle authorization exceptions.

https://github.com/ryanb/cancan

3. Haml (Better Views)

HAML transforms your views with sexy, minimalist syntax that makes Ruby jealous. HAML’s indent based syntax eliminates end tags, and provides a more concise way of defining HTML and interpreting embedded ruby code.

I made the switch about 2 years ago and cringe every time I have to work with “real” HTML. Even mediocre HTML ninjas will be comfortable with HAML in a few days. HAML takes:

1
2
<h2><%= @user.name %></h2>
<div class="about">About Me: <%= @user.about %></div>

and makes it great:

1
2
h2= @user.name
.about About Me: #{@user.about}

http://haml-lang.com/

4. Compass (Better CSS)

Compass is a framework that does to CSS what HAML does to HTML. In conjunction with SASS, a CSS replacement, Compass provides native frameworks such as Blueprint. By leveraging SASS mixins, you can finally ditch non-semantic classes such as “div-8″ for blueprint columns.

The other major benefit of SASS is variables, most commonly used for color definitions. Tear up that sticky note with hex colors and start using color variables. Better yet, create an entire color palette using SASS’s lighten and darken functions.

http://compass-style.org/

5. Will Paginate (Pagination)

Will Paginate is by far the reigning champ when it comes to pagination. Originally ported from PHP, will_paginate can get you up and running with pagination in a few lines of code. There are practically no contenders, and rightfully so since I can’t think of too many ways to make this better. OK, Ajax pagination would be really awesome.

https://github.com/mislav/will_paginate/wiki

6. Paperclip (File Attachments)

If you’ve ever written code to handle file uploads and image processing, you surely cringe every time a client says “I’d like the user to have his or her own photo”–that is until you’ve worked with a gem as easy to use as this one.

Paperclip makes it trivial to restrict content types, define storage locations and access a model’s associated attachment. If you’re working with images, you can define styles with corresponding resolutions for use-cases such as thumbnails and profile sizes.

Even if you are using Heroku with its read-only file system, paperclip works beautifully with outside storage mechanism such as Amazon S3.

https://github.com/thoughtbot/paperclip

7. Meta Where (ActiveRecord Query Extensions)

This is a less popular gem that I ran into when I got sick of passing in complex SQL strings into ARel where methods, and then finding the inconsistencies between MySQL (development) SQLite (test) and Postgres (Heroku).

The default behavior of chaining ARel where methods is to “and” the conditions. Meta_where lets you define complex boolean logic on conditions, even among sub tables.

http://metautonomo.us/projects/metawhere/

8. DelayedJob (Background Job Scheduling)

One of the easiest ways to speed up some Rails apps is to push more complex processing into background jobs. The most notorious offenders are image processing and emailing.

Instead of having the user wait on the browser while an email sends or an image is processed, (both items that can wait) offload these tasks to a later time and let the user continue.

This gem automatically handles scheduling and provides an easy way to run all scheduled jobs. With Heroku, running the jobs is as easy as pushing up the workers a notch.

https://github.com/tobi/delayed_job

9. Has Scope (Collection Filtering)

This gem does to filtering what will_paginate did to pagination. Most rails apps dealing with item collections that need to be filtered by an attribute such as location, category or tag, will benefit from this. By leveraging existing model scopes, you can keep your controllers lean without conditional statements for each possible filter query.

Simply use the has_scope method with the scope name in the controller, and pass the model into apply_scopes to take advantage instant filtering.

https://github.com/plataformatec/has_scope

10. Rack SSL Enforcer (HTTPS Redirection)

With all the hype a few months ago over Firesheep, even basic, non credit-card accepting, apps that use passwords need for SSL. Sure, there’s no requirement that you secure your app, and even if a user’s account was compromised it may cause little harm.

However, most people reuse the same password for everything, and I wouldn’t like to have on my conscience that a user’s online banking password was stolen because they accessed my app without SSL at Starbucks.

Rack SSL Enforcer is a dead simple gem that uses Rack to redirect non https requests to the https equivalent. The default configuration forces HTTPS on every request, but can easily be overridden to only required it on some URL and URL patterns.

You may be familiar with the ssl_requirement gem originally released by DHH. This isn’t compatible with Rails 3, although there is a fork bartt-ssl_requirement that is which I’ve used in previous projects. I never really liked the idea of HTTPS redirection happening after the request gets to the controller. The rack solution is much simpler, especially for securing an entire app.

https://github.com/tobmatth/rack-ssl-enforcer

Caching Techniques in Ruby on Rails

1. Basic Caching

This is an introduction to the three types of caching techniques that Rails provides by default without the use of any third party plugins.

To get started make sure config.action_controller.perform_caching is set to true for your environment. This flag is normally set in the corresponding config/environments/*.rb. By default, caching is disabled for development and test, and enabled for production.

config.action_controller.perform_caching = true

  1.1 Page Caching

Page caching is a Rails mechanism which allows the request for a generated page to be fulfilled by the webserver, without ever having to go through the Rails stack at all. Obviously, this is super-fast. Unfortunately, it can’t be applied to every situation (such as pages that need authentication) and since the webserver is literally just serving a file from the filesystem, cache expiration is an issue that needs to be dealt with.

So, how do you enable this super-fast cache behavior? Suppose you have a controller called ProductsController and an index action that lists all the products. You could enable caching for this action like this:

class ProductsController <

ActionController caches_page :index def index; end end

The first time anyone requests products/index, Rails will generate a file called index.html. If a web server see this file, it will be served in response to the next request for products/index, without your Rails application being called.

By default, the page cache directory is set to Rails.public_path (which is usually set to File.join(self.root, "public") – that is, the public directory under your Rails application’s root). This can be configured by changing the configuration setting config.action_controller.page_cache_directory. Changing the default from /public helps avoid naming conflicts, since you may want to put other static html in /public, but changing this will require web server reconfiguration to let the web server know where to serve the cached files from.

The page caching mechanism will automatically add a .html extension to requests for pages that do not have an extension to make it easy for the webserver to find those pages. This can be configured by changing the configuration setting config.action_controller.page_cache_extension.

In order to expire this page when a new product is added you could extend the products controller like this:

class ProductsController <

ActionController caches_page :index def index; end def create expire_page

:action => :index end end

If you want a more complicated expiration scheme, you can use cache sweepers to expire cached objects when things change. This is covered in the section on Sweepers.

Note: Page caching ignores all parameters, so /products/list?page=1 will be written out to the filesystem as /products/list.html and if someone requests /products/list?page=2, they will be returned the same result as page=1. Be careful when page caching GET parameters in the URL!

  1.2 Action Caching

One of the issues with page caching is that you cannot use it for pages that require checking code to determine whether the user should be permitted access. This is where Action Caching comes in. action caching works like page caching except for the fact that the incoming web request does go from the web server to the Rails stack and Action Pack so that before filters can be run on it before the cache is served. This allows you to use authentication and other restrictions while still serving the result of the output from a cached copy.

Clearing the cache works in the exact same way as with page caching.

Let’s say you only wanted authenticated users to edit or create a Product object, but still cache those pages:

class ProductsController <

ActionController before_filter :authenticate,:only => [ :edit, :create ]

caches_page :index caches_action :edit def index; end def create expire_page

:action => :index expire_action :action => :edit end def edit; end end

You can also use :if (or :unless) to pass a Proc that specifies when the action should be cached. Also, you can use :layout => false to cache without layout so that dynamic information in the layout such as the name of the logged-in user or the number of items in the cart can be left uncached. This feature is available as of Rails 2.2.

You can modify the default action cache path by passing a :cache_path option. This will be passed directly to ActionCachePath.path_for. This is handy for actions with multiple possible routes that should be cached differently. If a block is given, it is called with the current controller instance.

Finally, if you are using memcached, you can also pass :expires_in. In fact, all parameters not used by caches_action are sent to the underlying cache store.

  1.3 Fragment Caching

Life would be perfect if we could get away with caching the entire contents of a page or action and serving it out to the world. Unfortunately, dynamic web applications usually build pages with a variety of components not all of which have the same caching characteristics. In order to address such a dynamically created page where different parts of the page need to be cached and expired differently Rails provides a mechanism called Fragment Caching.

Fragment Caching allows a fragment of view logic to be wrapped in a cache block and served out of the cache store when the next request comes in.

As an example, if you wanted to show all the orders placed on your website in real time and didn’t want to cache that part of the page, but did want to cache the part of the page which lists all products available, you could use this piece of code:

<% Order.find_recent.each do |o|

%> <%= o.buyer.name %> bought <% o.product.name %> <% end

%> <% cache do %> All available products: <% Product.find(:all).each

do |p| %> <%= link_to p.name, product_url(p) %> <% end %> <%

end %>

The cache block in our example will bind to the action that called it and is written out to the same place as the action cache, which means that if you want to cache multiple fragments per action, you should provide an action_suffix to the cache call:

<% cache(:action => 'recent',

:action_suffix => 'all_prods') do %> All available products:

You can expire the cache using the expire_fragment method, like so:

expire_fragment(:controller =>

'products', :action => 'recent', :action_suffix => 'all_prods)

If you don’t want the cache block to bind to the action that called it, you can also use globally keyed fragments. To do this, call the cache method with a key, like so:

<% cache(:key =>

['all_available_products', @latest_product.created_at].join(':')) do %> All

available products: <% end %>

This fragment is then available to all actions in the ProductsController using the key and can be expired the same way:

expire_fragment(:key =>

['all_available_products', @latest_product.created_at].join(':'))

  1.4 Sweepers

Cache sweeping is a mechanism which allows you to get around having a ton of expire_{page,action,fragment} calls in your code. It does this by moving all the work required to expire cached content into na ActionController::Caching::Sweeper class. This class is an Observer that looks for changes to an object via callbacks, and when a change occurs it expires the caches associated with that object in an around or after filter.

Continuing with our Product controller example, we could rewrite it with a sweeper like this:

class StoreSweeper <

ActionController::Caching::Sweeper # This sweeper is going to keep an eye on the

Product model observe Product # If our sweeper detects that a Product was

created call this def after_create(product) expire_cache_for(product) end # If

our sweeper detects that a Product was updated call this def

after_update(product) expire_cache_for(product) end # If our sweeper detects

that a Product was deleted call this def after_destroy(product)

expire_cache_for(product) end private def expire_cache_for(record) # Expire the

list page now that we added a new product expire_page(:controller =>

'#{record}', :action => 'list') # Expire a fragment

expire_fragment(:controller => '#{record}', :action => 'recent',

:action_suffix => 'all_products') end end

The sweeper has to be added to the controller that will use it. So, if we wanted to expire the cached content for the list and edit actions when the create action was called, we could do the following:

class ProductsController <

ActionController before_filter :authenticate,:only => [ :edit, :create ]

caches_page :list caches_action :edit cache_sweeper :store_sweeper,:only =>

[ :create ] def list; end def create expire_page :action => :list

expire_action :action => :edit end def edit; end end

  1.5 SQL Caching

Query caching is a Rails feature that caches the result set returned by each query. If Rails encounters the same query again during the current request, it will used the cached result set as opposed to running the query against the database.

For example:

class ProductsController <

ActionController before_filter :authenticate,:only => [ :edit, :create ]

caches_page :list caches_action :edit cache_sweeper :store_sweeper,:only =>

[ :create ] def list # Run a find query Product.find(:all) ... # Run the same

query again Product.find(:all) end def create expire_page :action => :list

expire_action :action => :edit end def edit; end end

In the ‘list’ action above, the result set returned by the first Product.find(:all) will be cached and will be used to avoid querying the database again the second time that finder is called.

Query caches are created at the start of an action and destroyed at the end of that action and thus persist only for the duration of the action.

  1.6 Cache Stores

Rails (as of 2.1) provides different stores for the cached data created by action and fragment caches. Page caches are always stored on disk.

Rails 2.1 and above provide ActiveSupport::Cache::Store which can be used to cache strings. Some cache store implementations, like MemoryStore, are able to cache arbitrary Ruby objects, but don’t count on every cache store to be able to do that.

The default cache stores provided with Rails include:

1) ActiveSupport::Cache::MemoryStore: A cache store implementation which stores everything into memory in the same process. If you’re running multiple Ruby on Rails server processes (which is the case if you’re using mongrel_cluster or Phusion Passenger), then this means that your Rails server process instances won’t be able to share cache data with each other. If your application never performs manual cache item expiry (e.g. when you‘re using generational cache keys), then using MemoryStore is ok. Otherwise, consider carefully whether you should be using this cache store.

MemoryStoreis not only able to store strings, but also arbitrary Ruby objects. MemoryStoreis not thread-safe. Use SynchronizedMemoryStore instead if you

need thread-safety.

ActionController::Base.cache_store =

:memory_store

2) ActiveSupport::Cache::FileStore: Cached data is stored on the disk. This is the default store and the default path for this store is: /tmp/cache. Works well for all types of environments and allows all processes running from the same application directory to access the cached content. If /tmp/cache does not exist, the default store becomes MemoryStore.

ActionController::Base.cache_store =

:file_store, "/path/to/cache/directory"

3) ActiveSupport::Cache::DRbStore: Cached data is stored in a separate shared DRb process that all servers communicate with. This works for all environments and only keeps one cache around for all processes, but requires that you run and manage a separate DRb process.

ActionController::Base.cache_store =

:drb_store, "druby://localhost:9192"

4) MemCached store: Works like DRbStore, but uses Danga’s MemCache instead. Rails uses the bundled memcached-client gem by default. This is currently the most popular cache store for production websites.

Special features:

  • Clustering and load balancing. One can specify multiple memcached servers, and MemCacheStore will load balance between all available servers. If a server goes down, then MemCacheStore will ignore it until it goes back online.
  • Time-based expiry support. See write and the :expires_in option.
  • Per-request in memory cache for all communication with the MemCache server(s).

It also accepts a hash of additional options:

  • :namespace- specifies a string that will automatically be prepended to keys when accessing the memcached store.
  • :readonly- a boolean value that when set to true will make the store read-only, with an error raised on any attempt to write.
  • :multithread – a boolean value that adds thread safety to read/write operations – it is unlikely you’ll need to use this option as the Rails threadsafe! method offers the same functionality.

The read and write methods of the MemCacheStore accept an options hash too. When reading you can specify :raw => true to prevent the object being marshaled (by default this is false which means the raw value in the cache is passed to Marshal.load before being returned to you.)

When writing to the cache it is also possible to specify :raw => true. This means that the value is not passed to Marshal.dump before being stored in the cache (by default this is false).

The write method also accepts an :unless_exist flag which determines whether the memcached add (when true) or set (when false) method is used to store the item in the cache and an :expires_in option that specifies the time-to-live for the cached item in seconds.

ActionController::Base.cache_store =

:mem_cache_store, "localhost"

5) ActiveSupport::Cache::SynchronizedMemoryStore: Like ActiveSupport::Cache::MemoryStore but thread-safe.

ActionController::Base.cache_store =

:synchronized_memory_store

6) ActiveSupport::Cache::CompressedMemCacheStore: Works just like the regular MemCacheStore but uses GZip to decompress/compress on read/write.

ActionController::Base.cache_store =

:compressed_mem_cache_store, "localhost"

7) Custom store: You can define your own cache store (new in Rails 2.1)

ActionController::Base.cache_store =

MyOwnStore.new("parameter")

config.cache_store can be used in place of

ActionController::Base.cache_storein the Rails::Initializer.run block in

environment.rb.

In addition to all of this, Rails also adds the ActiveRecord::Base#cache_key method that generates a key using the class name, id and updated_at timestamp (if available).

An example:

Rails.cache.read("city") # => nil

Rails.cache.write("city", "Duckburgh") Rails.cache.read("city") # =>

"Duckburgh"

2. Conditional GET Support

Conditional GETs are a feature of the HTTP specification that provide a way for web servers to tell browsers that the response to a GET request hasn’t changed since the last request and can be safely pulled from the browser cache.

They work by using the HTTP_IF_NONE_MATCH and HTTP_IF_MODIFIED_SINCE headers to pass back and forth both a unique content identifier and the timestamp of when the content was last changed. If the browser makes a request where the content identifier (etag) or last modified since timestamp matches the server’s version then the server only needs to send back an empty response with a not modified status.

It is the server’s (i.e. our) responsibility to look for a last modified timestamp and the if-none-match header and determine whether or not to send back the full response. With conditional-get support in rails this is a pretty easy task:

class ProductsController <

ApplicationController def show @product = Product.find(params[:id]) # If the

request is stale according to the given timestamp and etag value # (i.e. it

needs to be processed again) then execute this block if stale?(:last_modified

=> @product.updated_at.utc, :etag => @product) respond_to do |wants| # ...

normal response processing end end # If the request is fresh (i.e. it's not

modified) then you don't need to do # anything. The default render checks for

this using the parameters # used in the previous call to stale? and will

automatically send a # :not_modified. So that's it, you're done. end

If you don’t have any special response processing and are using the default rendering mechanism (i.e. you’re not using respond_to or calling render yourself) then you’ve got an easy helper in fresh_when:

class ProductsController <

ApplicationController # This will automatically send back a :not_modified if the

request is fresh, # and will render the default template (product.*) if it's

stale. def show @product = Product.find(params[:id]) fresh_when :last_modified

=> @product.published_at.utc, :etag => @article end end

Source : http://blog.adroit-inc.com/web/caching-techniques-in-ruby-on-rails-3/167/

Are You the Best Ruby on Rails Developer You Know?

Photo by Naval History & Heritage Command.

Over the last few years, we have placed developers with a fairly wide range of skill sets.  Some are more junior developers with a year or two of experience.  Others are top-level guys/gals who have authored Rails books that are probably sitting on your bookshelf. 

If you are one of the top Rails developers at your company or in your circle of Rails pals, this post is for you. 

Having amazing Rails skills yourself is great and will make you a valuable asset at any company you choose to join.  But there is something that will make you infinitely more valuable: the ability to mentor other Rails developers.  If you are a good mentor, you have the ability to raise the level of work on your entire team, providing much greater value to your team, company, and the product or service you are building as a whole.  

It’s kind of like the Chinese proverb: “Give a man a fish; you have fed him for a day. Teach a man to fish; you have fed him for a lifetime.”  The ability to teach others fuels unprecedented growth and potential for your team.
 
If you have great Rails skills yourself, you are good to go.  But what will take you to that next level?  The ability to mentor those around you.  As an individual, even the best Rails developer has his/her limit in terms of the number of lines of code one can write and the number of bugs one can fix in a given time period.  But imagine if you could clone yourself (or the best developer at your company) through mentorship.  How much stronger would your team be?  How much better would your product be?

Source : http://mirrorplacement.com/blog/are-you-the-best-ruby-on-rails-developer-you-...

5 Signs You're Ready For a New Rails Job

Photo by Alex93vf.

 

It’s easy to get stuck in a job that’s no longer the right fit for you. Maybe it was exciting at first, but that was years ago and the company has changed. Or maybe you have changed. Either way, one of the biggest challenges in realizing it’s time for a new job is the simple but strong force of inertia. It’s much easier to stay put than it is to freshen up your resume, go on interviews, and ask for the job. So, to help you battle the power of inertia, here are some signs that you’re ready for your next Rails job:

  1. You’d much rather work on your own side projects than your 9-5 work. If your own side projects are consistently more engaging and fulfilling than your day job, it may be time for a new 9-5. Sure, side projects keep things interesting, but at the end of the day, they are still on the side. It makes no sense to spend all day, every day coding a project you’ve lost interest in. You wouldn’t work on a side project if it wasn’t fun. Why spend your most productive hours working on something you no longer enjoy?
  2. The dev team doesn’t get along or seems generally unhappy. If your coworkers are unhappy, it may be a sign that the development environment at your current place of work isn’t the best. Sometimes it’s easier to recognize discontent in others than it is in ourselves. A less-than-ideal development environment may be due to the company’s culture or it may be due to the individuals on the team (usually it’s some of both). Whichever it is, this is a tell-tale sign that you’re ready to engage with a new group of people.
  3. You rarely feel challenged. You might believe in the product or service you’re helping to build, but if your current role is underwhelming, it’s time for something new. This may be as easy as talking to your manager about new projects you can take on. Maybe there’s a particularly challenging area of the codebase you want to tackle but haven’t been given the chance to yet. Maybe you want to try your hand at some front-end dev work. Asking for a new challenge at your current job can fulfill this need, but sometimes we all need a fresh, new problem to gnaw on. The good news: there are lots of new, challenging problems out there waiting for problem-solvers just like you.
  4. You have a sneaking suspicion that you’re underpaid. You were chatting with some friends at this week’s Meetup about salaries and were pretty shocked to hear some details of their compensation packages. It’s not all about the money, but it doesn’t make sense to stay in a job where your skills are undervalued. Today’s market is paying top dollar for Rails developers with your skills. If your current company can’t get up to speed with market rate, you can be sure that other companies will.
  5. You see yourself doing the same thing 5 years from now. In an ideal job, you feel fulfilled, challenged, and in a constant state of growth and change. If you think about your future work and imagine yourself doing the exact same things you are now, you’re staring at a big red flag. Careers are meant to evolve and progress with different projects and challenges. You can find new ways to grow and learn at the same company, but oftentimes to move forward in your career, you need to seek an entirely new set of challenges provided by a new company.

Do any of these signs describe your current job situation? Don’t give into the power of inertia. At the end of your career, do you want to look back and say “well that was comfortable and easy”? Probably not. Once you’ve realized that you are indeed ready to explore other options, polish that resume and give us a shout!

Source : http://mirrorplacement.com/blog/5-signs-youre-ready-for-a-new-rails-job