Rails plugins
From WhyNotWiki
Libraries/plugins/tools/extensions/engines for Rails. (You might also be interested in Ruby libraries.)
Rails plugins and libraries edit (Category edit) .
Rails plugins and libraries / Installing and using edit
[edit] Can plugins be installed as gems (system-wide)?
Yes!
The Plugin Dependencies plugin[1], for example, can be installed as a gem.
Installation is simple:
> sudo gem install plugin_dependencies config/environment.rb: require 'plugin_dependencies' Rails::Initializer.run do |config| ...
With gems, you can even take advantage of gem dependencies. So instead of installing 5 plugins via Subversion (which is a pain, partly because you have to look up / remember the full URL of each plugin), you can just do a single gem install and it will automatically install the 5 plugins it depends on!
> sudo gem install plugins_plus Bulk updating Gem source index for: http://gems.rubyforge.org Install required dependency loaded_plugins? [Yn] Install required dependency appable_plugins? [Yn] Install required dependency plugin_routing? [Yn] Install required dependency plugin_assets? [Yn] Install required dependency plugin_migrations? [Yn]
[edit] Efforts to include gem plugin loading into core Rails
The fact that the above examples are possible is, I believe, unrelated to any special code within the Rails system to deal with gem plugins. In other words, I guess this has been possible all along, but few people actually released plugins as gems.
But it does require adding a "require" at the top of your config/environment.rb, before the Initializer is even run. And that's not very Rails-y.
Ticket #6726 ([PATCH] Add support for RubyGem-based plugins) in the Rails tracker, however, plans to change that. It would add support so that you can specify gem-based plugins in your config.plugins array:
config.plugins = ['foo', 'bar', 'baz', ['spam', '>0.9.0', '<=1.2.3'], 'eggs']
I, however, question the value of this ticket to people like me who would rather not use config.plugins in the first place, if possible, because it requires you to list out all your plugins...
Oh well, I'll keep watching this and see what comes of it...
http://dev.rubyonrails.org/ticket/6726
The trick with gem-based plugins is the fact that you might have many gem plugins installed, but might only want to use a small subset for any given application-- hence the use of config.plugins. Obviously using config.plugins is restrictive-- since if you are using "normal" path-based plugins you have to include them in the list for them to be enabled, but it is elective (and I consider the dependency-resolution mechanism that RubyGems offers well worth maintaining a config.plugins list).
As to how it works: Gems are loaded, then their lib/ paths are added to load_paths and load_once_paths as with any plugin (so autoloading works as expected). init.rb is also loaded in the same way as it is with the current path-based plugins (no need to specifically set it to be autorequired by the gem)-- this is so that 'config', etc are available to the plugin.
It seems like to benefit from the "dependency-resolution mechanism that RubyGems offers", you'd have to be using all gem-based plugins... I wonder how well all this works when you have a mix of gem-based and non-gem-based plugins...
[edit] Going the other way: unpacking gems and putting them in vendor/
There's an interesting command-line tool/gem called, GemsOnRails, that seems to take the exact opposite approach of gem-based plugins: rather than turning everything (including plugins) into gems, it recommends unpacking all gems into your vendor/ directory so that you wouldn't even be using RubyGems (for those libraries that you unpack)...
| "vendor everything"
|
|
| Homepage: | http://gemsonrails.rubyforge.org/
|
Link or freeze RubyGems into your rails apps, instead of just plugins. This allows you to ‘vendor everything’ – pushing all dependent gems into your rails app thus ensuring your application will be guaranteed to work when deployed. Your application is no longer dependent on the gems that are/aren’t available on your target deployment environment.
...
I actually fail to see what this has to do with Rails at all. Unpacking gems is a feature of RubyGems, not of Rails. All this plugin does (apparently) is provide some rake tasks to wrap the gem unpack command, and to enforce the convention that unpacked gems go into a vendor/gemsw subdirectory of your Rails app. Woop-de-doo.
Hmm, I guess another thing it does for Rails is auto-requires the library-that-was-formerly-a-gem-but-is-now-unpacked-under-vendor during app initialization. That's kind of handy. But still not very compelling. (It's not hard to add a require line to environment.rb...)
I'm not sure what this task actually does:
rake gems:link # Link a RubyGem into this Rails application; init.rb will be loaded on startup.
What is this "linking" you speak of, Dr. Nic?
The possibility of unpacking gems for the purpose of "ensuring your application will be guaranteed to work when deployed" is one I have considered before (see Gems or svn:externals?), and I'm still not sure what the best solution is.
If I ever did decide that unpacking gems was the best way to go, then I'd definitely want to give GemsOnRails a second look...
[edit] Specifying load order
[Problem (category)]: Sometimes your plugins need to be loaded in a specific order, due to dependencies. The plugin_dependencies plugin helps with that, but still only if it is loaded first (before the plugins that use it).
[Solution (category)]: The Plugin Dependencies plugin[2]
Problem: If you have plugins that require the plugin_dependencies plugin, then you have to (unless the plugin happens to be alphabetically later than 'p') use the config.plugins = directive in your environment.rb and explicitly list out all the plugins you want to be loaded. The problem with that: You're duplicating the list of plugins that already exists in the file system as the list of entries in vendor/plugins.
Solution:
Rather than list out all your plugins...
config.plugins = %W( plugin_dependencies annotate_models appable_plugins loaded_plugins ... )
You only need to explicitly the ones you want required first. Then you can say "then load the rest of the plugins using the default order" and it will...
config.plugins = ['plugin_dependencies'] + Dir.new('vendor/plugins').entries.reject {|f| f =~ /^\./}
I've also heard that it's possible to use "*" to do the same thing (tell it to load "the rest of the plugins"):
config.plugins = %W( plugin_dependencies * )
, but that didn't work for me with my version of Rails. I can't remember if they said it was available in edge Rails or with a certain plugin or what...
[edit] [Troubleshooting (category)] ./script/plugin install prompts you for a password
Example:
> ./script/plugin install whatever Authentication realm: <svn://delynnberry.com:3690> DeLynn's Code Repository Password for 'tyler':
Since you probably don't have a valid login to their repository (and never will), your available options are probably just one: "unsource" the offending plugin source.
First, you need to figure out the exact spelling of the source to remove:
> ./script/plugin sources | grep delynnberry.com svn://delynnberry.com/code/plugins/
Then simply unsource it:
> ./script/plugin unsource svn://delynnberry.com/code/plugins/ removed: svn://delynnberry.com/code/plugins/ Removed 1 repositories.
Rails plugins and libraries / Lower-level edit
[edit] [Ruby-level (category)]
(Ruby support libraries that are packaged as Rails plugins (unfortunately), as well as some that are plain old gems...)
[edit] Injection
| Categories/Tags: | [dependency injection (category)]
|
|---|---|
| Project/Development: | http://rubyforge.org/projects/injection/
|
| Description: | Injection is a simple dependency injection plugin for rails which lets you inject objects into your controllers which have been declared in a YAML file.
|
[edit] ActiveSupport
...
[edit]
Named Options
| As listed in other directories: | http://rubyfurnace.com/plugins/named_options
|
|---|
def user(*args) options = NamedOptions.new(:name, :age, args) options[:name] # => “maiha” options[:age] # => 14 end
Lets you call it using ordered arguments or with a hash of arguments/options...
user(“maiha”, 14) user(:name => ‘maiha’, :age => 14) user(“maiha”, :age => 14)
[edit] SandboxedMethods
http://rubyfurnace.com/plugins/sandboxed_methods
Avoid conflicting method and variable names between modules.
"We unconsciously prefer shorter names and tend to use well-conflictable method names such as ‘names’, ‘valid?’, ‘path’ for middle(internal) methods. Indeed it works sanely in your system, but how about outside of it?"
To use it, just change your module from this:
1 module Foo
2 def self.included(base)
3 base.__send__ :include, InstanceMethods
4 end
5
6 module InstanceMethods
...
16 end
17 end
to this:
1 module Foo
2 def self.included(base)
3 InstanceMethods.give(base, :foo) # 1) use 'give' class methods
4 end
5
6 class InstanceMethods < SandboxedMethods # 2) use SandboxedMethods class
...
16 end
17 end
It basically does this by prefixing each method with the name of the class ("class_name__method_name"?) and then delegating (?) all method calls...
http://wota.jp/svn/rails/plugins/trunk/sandboxed_methods/lib/sandboxed_methods.rb
def give(base, *methods)
target = (methods.last.is_a?(Hash) && methods.pop[:class]) ? (class<<base; self end) : base
methods = instance_methods - SandboxedMethods.instance_methods if methods.empty?
methods << {:to=>"(@_#{name.underscore.gsub('/', '__')} ||= #{self}.new(self))"}
target.delegate *methods
end
[edit] [Ruby-level (category)]: Dates and times
[edit] relative_time_helpers
| Rating: | ↓ |
|---|---|
| Homepage: | [3] |
| Source code: | http://ar-code.svn.engineyard.com/plugins/relative_time_helpers/
|
http://ar-code.svn.engineyard.com/plugins/relative_time_helpers/init.rb
# Used for getting multifield attributes like those generated by a
# select_datetime into a new Time object. For example if you have
# following <tt>params={:meetup=>{:"time(1i)=>..."}}</tt> just do
# following:
#
# <tt>Time.parse_from_attributes(params[:meetup], :time)</tt>
def parse_from_attributes(attrs, field, method=:gm)
attrs = attrs.keys.sort.grep(/^#{field.to_s}\(.+\)$/).map { |k| attrs[k] }
attrs.any? ? Time.send(method, *attrs) : nil
end
Con: They foist their date format preferences on you (Nov 15th, rather than 15 November or 11-15):
http://ar-code.svn.engineyard.com/plugins/relative_time_helpers/test/relative_time_helpers_test.rb
def test_should_show_date_span_on_the_different_year
assert_equal 'Nov 15th, 2006 - Dec 16th, 2007', relative_date_span([Time.utc(2006, 11, 15), Time.utc(2007, 12, 16)])
assert_equal 'Nov 15th, 2006 - Dec 16th, 2007', relative_date_span([Time.utc(2007, 12, 16), Time.utc(2006, 11, 15)])
end
[edit]
interpolated_time_formats
| Homepage: | http://wiki.pluginaweek.org/Interpolated_time_formats |
|---|---|
| Source code: | http://svn.pluginaweek.org/trunk/plugins/ruby/time/interpolated_time_formats
|
| As listed in other directories: | http://rubyfurnace.com/plugins/interpolated_time_formats
|
http://wiki.pluginaweek.org/Interpolated_time_formats
Rather than requiring the addition of helper methods, this plugin proposes creating such strings with strftime. For example,
>> Time.parse('12/31/2006').strftime('#{day.ordinalize} of %B') => "31st of December"
[edit] EZTime
http://users.webtest.wvu.edu/cbscharf/eztime/
puts d.eztime(":day :nmonth :year at :hour12::minute::second
:lmeridian")
=> 20 December 2003 at 5:30:00 pm
[edit] Date Finder
http://rubyfurnace.com/plugins/date_finder
Can find dates that match certain criteria. Eg:
The next three Tuesdays:
DateFinderBase.weekly.day(:tuesday).find(:max => 3)The last Monday for the next three months:
DateFinderBase.monthly.day(:monday).day_occurrence(:last).find(:max => 3)
- http://rubyfurnace.com/plugins/date_finder
- Repository Path: http://svn.viney.net.nz/things/rails/plugins/date_finder/
Note: This appears to have nothing at all to do with ActiveRecord searching (kind of deceptive, if you ask me, since it's packaged as a Rails plugin). Rather, it actually returns Date instances as the results of its "searches".
[edit] [library-level (category)]
[edit] object_id_session: Lets you store ActiveRecord models in the session using their IDs
http://rubyfurnace.com/plugins/object_id_session
A very simple plugin that allows to store ActiveRecord models over session using their IDs transparently.
session[:user] = User.find(id) # After this, your session will have :user => id and ?__user_object_id_session? => User.
- http://rubyfurnace.com/plugins/object_id_session
- Repository Path: svn://verbdev.com/rubylibs/object_id_session/trunk
- Homepage: http://rashkovskii.com/articles/2007/01/02/object_id_session
[edit]
[GnuPG (category)] plugin [API wrappers for command-line applications (category)]
| Homepage: | http://www.ahgsoftware.com/pages/erb_buffer |
|---|---|
| Source code: | svn://ahgsoftware.com/gnupg/trunk
|
| As listed in other directories: | http://rubyfurnace.com/plugins/gnupg
|
passphrase = "uglydonkeys"
gnupg = GnuPG.new :binary=>"/opt/local/bin/gpg",
:workdir=>workdir,
:homedir_pub=>workdir,
:homedir_sec=>workdir,
:recipient=>"your uid"
plain_message = "my secret message"
encrypted_message = gnupg.encrypt(plain_message)
gnupg.load_key File.read("sec_key.asc")
decrypted_message = gnupg.decrypt(encrypted_message, passphrase)
gnupg.drop_key
[edit] RailMail
http://railmail.nullstyle.com/
Advantages:
- Logs all outgoing e-mail to a database table. Much nicer to read/search than the log file, which is where it gets logged by default.
- Why would you want to see what's been sent? Maybe if someone claims they never received an e-mail you sent, you could check the logs easily and see. (Even if it appears that you did already send it, this would make it easier to resend.)
- Less dependencies on your development box. No need to set up outgoing mail on your box or even have an Internet connection. Just check the RailMail log to see if it went out.
- Can test your application with addresses other than your own and not worry about bothering other people. (This could also be solved by using a much simpler plugin that just overrode ActionMailer to have it deliver all outgoing messages to you regardless of original recipient.)
Problems:
- Don't fallaciously assume e-mail is going out successfully just because it is logged by RailMail. Manual testing of e-mails on live server will still be necessary.
- Does having a message in the RailsMail log mean that it was sent? Apparently, you need to set railmail_settings[:passthrough] = :smtp in order for mail to actually be sent. So maybe it should log the value of passthrough for each logged message so you know if it was actually passed through to SMTP or not.
Conclusion: Seems like overkill to me. Maybe some applications would have more need of e-mail logging, but I probably typically wouldn't.
[edit] Permissions/Security
[edit] ModelSecurity
http://weblog.rubyonrails.com/2005/11/11/why-engines-and-components-are-not-evil-but-distracting McNewby, 2005-11-16 05:50:
- However, from an infrastructural perspective, I like the thinking of ModelSecurity – in as much as permissions should at least begin in the Model (and hopefully ripple out to the UI). It should be possible to develop Rails such that permissions can be automatically ‘discovered’, e.g. for every attribute, there’s only three options: no access, read, write. Likewise for each method, there’s only two: can run, can’t run…
[edit] secure-action-plugin
http://rubyfurnace.com/plugins/secure_action_plugin
- secure-action-plugin provides an easy to use interface for protecting your app against assumed logged in attacks
Rails plugins and libraries / Database-level edit
[edit] [ActiveRecord/database-level (category)]
[edit] ActiveWarehouse
http://activewarehouse.rubyforge.org/
[edit] Appable plugins: distribute models in your plugin
See Rails plugins and libraries / Plugin tools#Appable plugins
[edit] redhillonrails_core
http://www.redhillconsulting.com.au/rails_plugins.html
http://www.redhillconsulting.com.au/rails_plugins.html#redhillonrails_core
- The plugin provides two mechanisms for adding foreign keys as well as preserving foreign keys when performing a schema dump.
-
t.foreign_key :customer_id, :customers, :id
[edit] ActiveRecord Defaults
http://rubyfurnace.com/plugins/activerecord_defaults
- Allow you to easily specify default values for attributes on new model objects.
How does this compare to having the defaults stored in the database?
[edit] [ActiveRecord/database-level (category)]: Migrations
[edit] Migrate "development" and "test" databases simultaneously
[edit] When would you not want to?
I've had numerous occasions where I wonder why my test isn't passing, only to eventually find out that I hadn't migrated the test database yet, only development. I had done manual testing with the development environment, and everything had worked beautifully, so I was mystified why it wouldn't work in test.
[edit] (The plugin)
[To do: Soon to be released]
[edit]
Transactional Migrations
| Homepage: | http://www.redhillonrails.org/#transactional_migrations |
|---|---|
| Source code: | svn://rubyforge.org/var/svn/redhillonrails/trunk/vendor/plugins/transactional_migrations
|
| Description: | Transactional Migrations is a plugin that ensures your migration scripts—both up and down—run within a transaction. When used in conjunction with a database that supports transactional Data Definition Language (DDL)—such as PostgreSQL—this ensures that if any statement within your migration script fails, the entire script is rolled back.
|
| License: | [[:MIT license|MIT license]]
|
| Authors: | Red Hills Consulting
|
rake db:migrate:plugins # Migrates both acts_as_bunny and acts_as_chicken rake db:migrate:plugins PLUGIN=acts_as_bunny rake db:migrate:plugins PLUGIN=acts_as_bunny VERSION=2
[edit]
Plugin migrations
| Homepage: | http://wiki.pluginaweek.org/Plugin_migrations |
|---|---|
| Documentation: | Readme |
| Source code: | script/plugin install -x http://svn.pluginaweek.org/trunk/plugins/active_record/migrations/plugin_migrations |
| Project/Development: | http://dev.pluginaweek.org/browser/trunk/plugins/active_record/migrations/plugin_migrations |
| As listed in other directories: | http://rubyfurnace.com/plugins/plugin_migrations |
| Description: | plugin_migrations adds the abilities for all plugins to have the same migration capabilities that your Rails application has. It does this by adding a new table called plugin_schema_info to keep track of the migration version of each plugin.
|
[edit] Installation
script/plugin install -x http://svn.pluginaweek.org/trunk/plugins/rails/loaded_plugins/ script/plugin install -x http://svn.pluginaweek.org/trunk/plugins/active_record/migrations/plugin_migrations
[edit] Usage
Just create a db/migrate directory within your plugin's directory and throw some plugin-specific migrations (creating tables, most likely) in it and you're set!
Then when the user installs your plugin, they can simply run rake db:migrate:plugins to run those migrations!
(Much better than creating a migration generator, I think.)
rake db:migrate:plugins rake db:migrate:plugins # Migrates all loaded plugins rake db:migrate:plugins PLUGIN=acts_as_commentable rake db:migrate:plugins PLUGIN=acts_as_commentable VERSION=2
[edit]
DSL-style migrations
Makes your migrations a little DRYer.
http://habtm.com/articles/2006/12/26/dsl-style-migration
class CreateAccounts < Special::Migrations::Table table_name :accounts column :login, :string column :email, :string column :created_at, :datetime options[:force] = true end
Pope Says: December 26th, 2006 at 07:10 AM
as for maintainable, it may not in the area you are thinking about. Since going down is just the opposite of going up, why try to make sure that you keep those two in sync? I have run into situations where going down broke something, most of the time due to a typo or because something was forgotten. Since this seems to look like it takes care of that, it becomes one less thing you have to maintain.
I can see a complaint with it that it may be too customized. I have fallen in this pitfall of metaprogramming where i get so into it, that it becomes less readable. That is because this way of thinking about migrations solves the majority of the problems; however, for some of the other problems, a user would have to resort back to using the old system. That means that someone using this would have to be familiar with both ways to do it.
That problem now falls on the user of this special system as to if he/she wants to use it or not.
David Says: December 26th, 2006 at 08:39 PM
> I usually rewrite migration files and remigrate database via > VERSION=0 again and again.
Yeah, I do this a lot during initial development, so maintainability does count.
Jason Says: December 28th, 2006 at 12:43 AM
Wow, you guys really take the DRY concept way too far. DRY is nice and it’s one of the reasons I love rails but come on, “redundant temporary variable ‘t’ in ‘create_table’ block”? That’s just silly.
- http://rubyfurnace.com/plugins/migration2
- Repository Path: http://wota.jp/svn/rails/plugins/branches/stable/migration2/
- Homepage: http://habtm.com/articles/2006/12/26/dsl-style-migration
[edit]
Migratory Shortcuts
Migrations are truly a great addition to Rails. That said, if you have a boat load of tables in your project it can be pretty tedious to keep repeating the same values [column specifications] again and again.
Somewhere in the middle of doing this…
create_table :actors do |t| t.column "created_at", :datetime t.column "updated_at", :datetime t.column "deleted", :boolean, :null => false, :default => false end create_table :names do |t| t.column "name", :string, :null => false t.column "created_at", :datetime t.column "updated_at", :datetime t.column "created_by", :integer, :null => false t.column "updated_by", :integer, :null => false t.column "deleted", :boolean, :null => false, :default => false end create_table :actors_names do |t| t.column "actor_id", :integer, :null => false t.column "name_id", :integer, :null => false t.column "position", :integer, :null => false, :default => 0 t.column "created_at", :datetime t.column "updated_at", :datetime t.column "created_by", :integer, :null => false t.column "updated_by", :integer, :null => false t.column "deleted", :boolean, :null => false, :default => false endfor the tenth time, you begin to wonder if there is a better way.
Introducing.. a better way.
The above becomes this…
create_table :actors, :with => [:timestamps,:userstamps,:acts_as_paranoid] create_table :names, :with => [:timestamps,:userstamps,:acts_as_paranoid] do |t| t.column "name", :string, :null => false end create_link_table :actors, :names, :with => [:timestamps, :userstamps, :acts_as_paranoid, :acts_as_list]This makes dealing with migrations just a bit more manageable, and you no longer need to remember all the “magic” column names. Just say “acts_as_list” and the “position” column is added for you.
Thus far the following options are supported:
- acts_as_list
- acts_as_tree
- acts_as_nested_set
- acts_as_paranoid
- timestamps
- userstamps
- script/plugin install svn://rubyforge.org/var/svn/rubybrain/rails/plugins/migratory_shortcuts
- Repository Path: svn://rubyforge.org/var/svn/rubybrain/rails/plugins/migratory_shortcuts
- Homepage: http://www.rubybrain.org/articles/4-DRYing-up-migrations-revisited
[edit] subverted_migrations
http://rubyfurnace.com/plugins/subverted_migrations
This plugin makes it easier to use Rails migrations with Subversion (when working with multiple branches).
It has two main features:
- Ensures unique version numbers across the trunk and branches
- Keeps track of which migrations have been applied to the database, and applies new migrations when merged in to the branch.
- http://rubyfurnace.com/plugins/subverted_migrations
- Repository Path: svn://svn.madriska.com/plugins/subverted_migrations
- Homepage: http://www.bradediger.com/blog/2006/11/subverted_migrations.html
[edit] [ActiveRecord/database-level (category)]: [Searching (category)] / query building
See also Ruby libraries#Database
[edit] acts_as_locateable
| Categories/Tags: | [searching (category)][acts_as_plugins (category)] |
|---|---|
| Homepage: | http://www.baconbear.com/articles/2006/12/29/actsaslocateable-released |
| Source code: | http://svn.baconbear.com/rails_plugins/acts_as_locateable/trunk/
|
| As listed in other directories: | http://rubyfurnace.com/plugins/actsaslocateable |
| Description: | [[description := ActsAsLocateable is an easy way to give any model the ability to be found by location.[4]|ActsAsLocateable is an easy way to give any model the ability to be found by location.[5]]]
|
http://www.baconbear.com/articles/2006/12/29/actsaslocateable-released
ActsAsLocateable is an easy way to give any model the ability to be found by location. For instance, say you have a model Store which is associated with a zip code indicating where that Store is located. To find all the stores within a specific radius of another ZipCode, you can do a
Store.find_within_radius(10, 12345) # Find all stores within 10 miles of zip code 12345
Based on: the ZipCodeSearch plugin (heavily)
[edit] ZipCodeSearch
| Categories/Tags: | [searching (category)] |
|---|---|
| Homepage: | http://zipcodesearch.rubyforge.org/ |
| Source code: | svn://rubyforge.org/var/svn/zipcodesearch/trunk
|
| As listed in other directories: | http://rubyfurnace.com/plugins/zipcodesearch
|
http://zipcodesearch.rubyforge.org/
ZipCodeSearch is a Rails plugin that makes implementing location-based searches a cinch. If you've ever wondered how to do location-based radius searches in your snazzy new Web 2.0 application, then this plugin might save you some time.
This plugin will create a ZipCode model, which contains all the code for calculating distances and searching. This plugin will also create a migration that adds a zip code table to your database, complete with 45,000 zip codes and with their lat/lon and city/state information. Finally, this plugin will generate a fully functional controller/view that contains a simple example of how to use the ZipCode model for your location searches.
[edit]
ez-where [DSLs (category)]
Very intuitive.
A couple neat examples (http://brainspl.at/articles/tag/where):
options = Article.find_where_options do |article|
article.comments.user.name == 'Fab'
article.and( (article.c.title =~ 'A%') | (article.c.title =~ 'B%') )
article.comments.any do
body =~ 'Lorem%'
body =~ 'Ipsum%'
end
end
cond = c{ title =~ '%ruby%' }
cond += c{ description =~ '%ez-where%' }
cond |= c{ user_id === (1..5) }
cond -= c{ pub_date > Time.now.to_s(:db) }
Post.find :all, :conditions => cond
=> ["((title LIKE ?) AND (description LIKE ?))
OR ((user_id IN (?)) AND NOT (pub_date > ?))",
"%ruby%", "%ez-where%", [1, 2, 3, 4, 5], "2006-06-21 01:17:47
http://brainspl.at/articles/2006/01/30/i-have-been-busy
./script/plugin install http://opensvn.csie.org/ezra/rails/plugins/dev/ez_where/
http://rubyforge.org/projects/ez-where/
[edit]
CriteriaQuery [DSLs (category)]
Description [6]:
CriteriaQuery is an extension to the ActiveRecord find mechanism. It allows object-oriented construction of queries.
Examples: [7]
[8]Person.query.name_like(‘name’).join(‘address’).city_like(‘city’).join(‘state’).name_eq(‘state’)instead of
Person.find(:all, :conditions=>[‘people.name LIKE ? AND addresses.city LIKE ? AND states.name=?’, ‘name’, ‘city’, ‘state’], :include=>[:city=>[:state]])
pq = Person.query pq.name_like('name') pq.join('address') do |address| address.or do |streets| streets.street_1_like('street).street_2_like('street) end endpq = Person.query pq.join(:lives_in) pq.join(:works_in) pq.or << pq.lives_in.street_eq('some_street') << pq.works_in.street_eq('some_street')
Features:
- Available expressions:
- Equals
- Not equal
- Like
- Greater than
- Greater than or equal
- Less than
- Less than or equal
- Is null
- Not null
- In
- Available subrestrictions
- Disjunction (OR)
- Conjunction (AND)
- Negation
- Supports joins across multiple associations
- Supports joining the same table multiple times
- http://rubyfurnace.com/plugins/criteria_query
- Repository Path: svn://rubyforge.org/var/svn/criteriaquery
- RDoc: http://www.muermann.org/ruby/criteria_query/ (great page -- lots of examples)
[edit] acts_as_solr
| Categories/Tags: | [full-text search (category)][acts_as plugins (category)] |
|---|---|
| Homepage: | http://acts-as-solr.rubyforge.org/ |
| Source code: | http://opensvn.csie.org/thiago/rails/plugins/acts_as_solr/
|
| As listed in other directories: | http://rubyfurnace.com/plugins/acts_as_solr
|
http://rubyfurnace.com/plugins/acts_as_solr:
This plugin adds full text search capabilities using Solr to any Rails model.
[edit] Live search
(very "cool"!)
http://www.recentrambles.com/pragmatic/view/59
[edit] Query by example
http://blog.codahale.com/2006/02/04/a-rails-howto-query-by-example/
[edit] Squirrel
http://giantrobots.thoughtbot.com/2006/9/29/an-improvement-for-querying-in-rails
[edit] Query builder
http://rubyfurnace.com/plugins/query_builder
This plugin enables you to define finder methods that bypass the overhead of construct_finder_sql.
Inside an ActiveRecord model definition,
define_finder query_name, query_type, options_hashwill create a SQL query method called query_name from a given options_hash. query_type can be :first or :all.
The plugin supports all options except :include, but ignores with_scope options.
Example:
class Recipe define_finder :find_all_of_user, :all, :conditions => 'user = :user AND priv < :priv' endThis defines a query method which can be called like so:
Recipe.find_all_of_user :user => 'martin', :priv => 1This call is equivalent to
Recipe.find :all, :conditions => ['user = :user AND priv < :priv', {:user => 'martin', :priv => 1}]
- http://rubyfurnace.com/plugins/query_builder
- Repository Path: http://railsexpress.de/svn/plugins/query_builder/trunk/
- Homepage: http://railsexpress.de/blog/articles/2006/09/23/new-plugin-query_builder
[edit]
Condition Builder
http://rubyfurnace.com/plugins/condition_builder
Book.find(:all,
:include => {:content_pointer => :invitees},
:conditions => Condition.block { |c|
c.and "invitees.user_id", self.id
c.and "content_pointers.created_by_id", self.id
c.and "content_pointers.company_id", company.id if company
})
- http://rubyfurnace.com/plugins/condition_builder
- Repository Path: http://inquirylabs.com/downloads/condition-builder-1.0.tgz
- Homepage: http://blog.inquirylabs.com/2007/01/04/condition-builder-10-released/
[edit] conditioner
http://www.bigbold.com/snippets/posts/show/2510
Converts arrays of this form:
[['user_id', 3], ['job_id', 4]
into ActiveRecord conditions form:
["user_id=? AND job_id=?", 3, 4]
[edit] SodaSearch
| Homepage: | http://sodasearch.rubyforge.org/ |
|---|---|
| Source code: | svn://rubyforge.org/var/svn/sodasearch |
| Project/Development: | http://rubyforge.org/projects/sodasearch/
|
| Description: | SodaSearch is a drop-in full text indexer plugin for Ruby on Rails. It allows coders to add full text indexing to their models with minimal effort. The index is stored as two regular tables in your project's existing RDBMS.
|
Soda Search is a medium-performance full-text indexing system. It is loosely based on the same principles as Xapian (www.xapian.org/).
The system is relatively simple. It consists of two database tables per class being indexed, plus some ActiveRecord extensions shared by all classes that use the Indexer.
The database tables are deliberately NOT normalized completely, to cut back on the computational overhead required to do searches and updates.
This system is quite useable as it is, but the index format it provides is also the foundation for a much more robust searching system. We will eventually implement phrase matching, term weighting, Boolean term combination, etc. This can all be accomplished with the current index format; all that needs to be done is modify the searching code.
Rails plugins and libraries / Model-level edit
[edit] [Model-level (category)]
http://wiki.rubyonrails.org/rails/pages/Model+Extensions
[edit] SemanticAttributes
| Rating: | ![]() |
|---|---|
| Categories/Tags: | [Validations ( |