Posting to Twitter from a Ruby on Rails App | ckdake.com Similar to Tuesday's Posting to Facebook post, here is how to link a model in a Ruby on Rails app with Twitter and post to Twitter. This one does the exact same thing, but of course needs to use different code because everyone implements OAuth differently. To post to Twitter, I use the OAuth gem to connect, and the Twitter Gem to do posting. Note that this uses the 1.0 version of the Twitter gem which is not yet released, so the Gemfile pulls it from Github directly. Read The Twitter Docs, specifically the Twitter OAuth Docs. The basic flow here for the user is the same as with Facebook: User visits twitter_account/new when they want to link in TwitterThey get redirected to the allow/deny page on Twitter that prompts the user to log in and accept your applicationAssuming they accept, they get redirected back to callback/twitter/ with an oauth_token that we use to look up the TwitterAccount (a nice feature that Facebook doesn't do!) Run "bundle install" and set up the routes:
Loading a single fixture in rails. | stew (@) rtmatheson.com UPDATE: At the time of this posting I did not know that there was already a way to do this in rails but thanks to Robert Siemieniec for letting me know. rake db:fixtures:load FIXTURES=name_of_fix_file,name_of_other_fix_file So just use this in the future. My solution still works if you wanted to have a separate rake task. However honestly there is no point just go with what rails has out of the box. If you really want to have your own rake task then read on. namespace :db do namespace :fixtures do desc "Load a single fixture by setting FIXTURE=name of fixture you wish to laod." task :load_single => :environment do require 'active_record/fixtures' ActiveRecord::Base.establish_connection(ActiveRecord::Base.configurations[RAILS_ENV]) Fixtures.create_fixtures("test/fixtures", [ENV['FIXTURE']]) puts "Fixture #{ENV['FIXTURE']} loaded in to #{RAILS_ENV} environment." end end end Usage… rake db:fixtures:load_single FIXTURES=questions
Use memoization Memoization is an optimization technique used primarily to speed up computer programs by having function call avoid repeat the calculation of results for previously-processed input. Here I will give you an example. Problem Imagine you have a billing system that one user has many accounts, each account has its own budget, there is a method total_budget for user object, which calculate the summary of all the available accounts' budgets. The following is the model definition. class User < ActiveRecord::Base has_many :available_accounts, :class_name => 'Account', :conditions => "budget > 0" def total_budget self.available_accounts.inject(0) { |sum, a| sum += a.budget } endend total_budget will be used multiple times in models, views and controllers, such as <% if current_user.total_budget > 0 %><%= current_user.total_budget %><% end %> Caching with instance variable There is an easy solution to use caching with instance variable to avoid the duplication execution. def has_comment? Memoizable
Successful Freelancing With Ruby On Rails: Workflow, Techniques And Tools - Smashing Magazine Advertisement Warning: Freelancing Is Not for Everyone A freelancer is a self-employed person who pursues a profession without a long-term commitment to any particular employer. Your curiosity in this opportunity was probably sparked by posts marked “Freelance” or “Work from anywhere” on the myriad of job boards around the Web. Freelancing is equal parts freedom and responsibility. While you have the freedom to choose when you work, where you work and what you work on, you are also responsible for everything: deadlines, finding work, the quality of your work, communication and so much more. Photo by Dmitry Belitsky Ruby, with all of its frameworks and libraries (such as Rails, Merb and Sinatra), is a practical tool to use in your freelance Web development career because of its focus on clean code, object-oriented syntax, efficient development practices and strong community (whether a simple IRC chat room or large conference). Pros Photo by Giorgio Montersino. Be your own boss. Cons Job Boards
SimplestAuth: Gem-ified, with DataMapper Support | Viget Extend A few months ago we released simplest_auth as a stripped-down alternative to authentication plugins such as restful auth. After using it in a few projects we came to the realization that there was no particular reason for it to be a plugin and even less of a reason for it to work only with ActiveRecord. As a result, the latest version on Github is now built as a gem and can be used in a Rails project that is using either ActiveRecord or DataMapper as its ORM. The same example usage from the README applies to ActiveRecord, but I'd like to give an example which uses DataMapper for the model. class User include DataMapper::Resource include SimplestAuth::Model property :id, Serial property :email, String, :nullable => false property :crypted_password, String, :length => 60 # validate your model as you see fit # these are some sane defaults for password validates_present :password, :if => :password_required? validates_is_confirmed :password, :if => :password_required?
Crazy, Heretical, and Awesome: The Way I Write Rails Apps | James on Software Mar 21, 2010 Note: This is going to sound crazy at first, but bear with me. The current best-practice for writing rails code dictates that your business logic belongs in your model objects. Before that, it wasn't uncommon to see business logic scattered all over controller actions and even view code. Pushing business logic in to models makes apps easier to understand and test. I used this technique rather successfully for quite some time. As applications grew, test suites would get slow — like minutes slow. But slow tests are bad. Also, coupling all of your business logic to your persistence objects can have weird side-effects. When we deploy new features to production, we roll them out selectively. If calling #save triggers version 1 of the business logic, then you're basically out of luck. Here Comes the Crazy Part The solution is actually pretty simple. Let's look at the first example I mentioned: logging the creation of a user. The specs: Yeah, it's true.
[EXCEL]Ary Djmal / to_xls Plugin: Export to Excel in Rails the Easy Way Looking at the Google Analytics stats I realized that a lot of people are still reading my blog post about how to export to Excel in Rails. IMO I prefer the csv method because it provides the same + more at no extra cost, but given people still wants xls files I wrote another rails plugin: to_xls. UPDATE: SuperSaaS (Thanks!) mentioned that Excel does not interpret UTF8 characters in CSV files. So if that is a concern to you, maybe you should stick with XLS. Using this plugin you don't need the builder views, so it makes it as easy as the to_csv plugin I wrote. In config/initializers/mime_types.rb register the custom mime type. Mime::Type.register "application/vnd.ms-excel", :xls In the controller where you want to export to excel, add the format.xls line. That's it! Install .
[ARRAY-SELECT] A Rails HOWTO: Query By Example | Archives | codablog | Coda Hale A Rails HOWTO: Query By Example So I was hanging out in #rubyonrails yesterday, and someone asked a great question: (10:40:53) jbwiv: guys, does Rails have the equivalent of hibernate's query by example? (10:41:39) jbwiv: By QBE, I mean I can create an object, set fields on that object, and then query the database by providing that object as an example. Does rails (active record) have an equivalent? The answer is interesting: no, but adding that’s a snap. Wanna see how? Update 2/19/2006: find_by_example now takes arrays as parameters. Update 2/6/2006: One of the folks in #rubyonrails pointed out a possible security problem with this, if the attributes list is taken directly from the user. First, we know we’re going to be extending one of the classes in ActiveRecord, so here’s the game plan: Query By Example Let’s add #find_all_by_example as a class method of ActiveRecord::Base. Behold: A weird example Pop quiz, hot shot. Witness the fitness: Have fun!
5 Rails Plugins to Help Optimize Your MySQL Optimizing your MySQL queries and performance in your rails applicationcan be a real pain. The plugins below help to make things a little easier. Bullet Bullet is a rails plugin, written by Richard Huang (@flyerhzm), that helps to kill N+1 queries. It shows you where you should be using :include in your ActiveRecord calls. Bullet also informs you where you’re missing counter caches as well as warning you of any unused eager loading. SlimScrooge SlimScrooge is a plugin by Stephen Sykes (@sdsykes), that restricts the columns retrieved in your MySQL queries by learning which attributes are subsequently called on the ActiveRecord model. Below is an example, taken from the readme: Query Reviewer Query Reviewer by David Stevenson (@dsboulder) of Pivotal Labs, is a Rails plugin that adds a div to the top left of the screen that contains lots of useful details regarding the MySQL executed on the current page. Rails Indexes
Exportando dados para Excel usando CSV em um aplicativo Rails | Plataforma Tecnologia Blog To see this post in English, click here. Às vezes os usuários querem manipular os dados de diversos modos. Nesses cenários, é comum exportar os dados num formato de tabela para que se possa usar um editor de planilhas e então filtrar, particionar e mudar os dados da forma que o usuário quiser. Generalmente, fazemos isso usando CSV, certo? O OpenOffice e outros editores podem abrir arquivos CSV sem problemas. Entretanto, o Excel não funciona exatamente da mesma forma. Tendo isso em mente, é assim que fazemos na Plataforma para lidar com os formatos do Excel. É TSV, e não CSV, rapaz! O Excel espera que seus dados venham com tabulações como separador de campo. Se você está usando o FasterCSV, só precisa fazer: Não esqueça! Sem quebras de linha nos campos O Excel não gosta quando você põe um “\n” dentro dos campos. Então, se você tem campos de texto no seu modelo, tome cuidado. Esqueça UTF-8. Alguns até dizem que este é o único formato Unicode suportado pelo Excel. Resumindo