When Paperclip attachments should only be downloadable for selected users, there are three ways to go.
The same applies to files in Carrierwave.
The first way is to store Paperclip attachments not in the default public/system
, but in a private path like storage
inside the current release. You should prefer this method when dealing with sensitive data.
Make ...
In modern Rails versions you can also use ActiveRecord's pluck
method.
>> User.active.pluck(:id)
=> [1, 5, 23, 42]
If you are plucking from the id
column in particular you can also say:
>> User.active.ids
=> [1, 5, 23, 42]
For a DISTINCT
selection, use distinct
on your scope (not the resulting array).
>> Article.distinct.pluck(...
You should test the callback methods and its correct invocation in two separate tests. Understand the ActiveRecord note before you move on with this note.
Say this is your Spaceship
class with a transition launch
and a release_docking_clamps
callback:
class Spaceship
state_machine :state, :initial => :docked do
event :launch do
transition :docked => :en_route
end
before_transition :on => :launch, :do => :release_doc...
You can use the whatlanguage gem to detect the language of a Ruby string.
Note that it also has not been updated in quite a while and that there might be alternatives. However, it still works.
It has problems with short strings, but works quite well on longer texts.
Use it like this:
>> WhatLanguage.new(:all).language('Half the price of a hotel for twice the space')
=> :english
There is also a convenience method on Strings (you may need to require 'whatlanguage/string'
).
>> 'Wir ent...
When you load a record with find options that have SQL fragments in :select
or :joins
, ActiveRecord will make that record read-only. This is a protective measure by Rails because such a record might have some additional attributes that don't correspond to actual table columns.
You can override that precaution by appending :readonly => false
to affected find options or scope options.
This post explains, in some detail, how we will implement a nice performance boost for Rails developers. Understanding the details might help gain the full benefits of the optimization, but you will gain some benefits even if you have no idea how it works.
When you need to add a event listener to hundreds of elements, this might slow down the browser.
An alternative is to register an event listener at the root of the DOM tree (document
). Then wait for events to bubble up and check whether the triggering element (event.target
) matches the selector before you run your callback.
This technique is called event delegation.
Because you only register a single listener, registering is ...
When working with times and dates in Rails applications, you need to deal with the following problem:
Time
objects have a time zone. You can get the zone name by doing time_object.zone
.Rails has two completely different modes ...
jamesgolick / resource_controller at Github
module ResourceController
module Actions
def index
load_collection
before :index
response_for :index
end
def show
load_object
before :show
response_for :show
rescue ActiveRecord::RecordNotFound
response_for :show_fails
end
def create
build_o...
When doing a query like this:
SELECT id FROM users
WHERE (users
.id
IN (899,1084,1095,100,2424,2429,2420))
the order of the returned records is undefined. To force the query to return the records in a given order, you have to add ORDER BY FIELD(id, 899, 1084, ...)
So the query looks like this:
SELECT id FROM users
WHERE (users
.id
IN (899,1084,1095,100,2424,2429,2420)) ORDER BY FIELD(id,899,1084,1095,100,2424,2429,2420);
An alternative to this technique is using VCR. VCR allows you to record and replay real HTTP responses, saving you the effort to stub out request/response cycles in close details. If your tests do require close inspection of requests and responses, Webmock is still the way.
WebMock is an alternative to FakeWeb when testing code that uses the network. You sh...
Open the configuration file:
gksudo gedit /usr/share/vte/termcap/xterm
Find a line like this:
:co#80:it#8:li#24:\
Change the first and last number to your desired columns and rows:
:co#160:it#8:li#40:\
Save your changes and close all open terminals. New terminals should now open with the new size.
In a nutshell: to avoid your shell character set from messing with imports, use -r
to export and SOURCE
when importing.
# Do not do this, since it might screw up encoding
mysqldump -uroot -p database > utf8.dump # this is bad
Better do:
mysqldump -uroot -p database -r utf8.dump
Note that when your MySQL server is not set to UTF-8 you need to do mysqldump --default-character-set=latin1
(!) to get a correctly e...
First do
ALTER DATABASE database_name CHARACTER SET "utf8";
ALTER DATABASE database_name COLLATE "utf8_unicode_ci";
After that, for each table:
ALTER TABLE table_name DEFAULT CHARACTER SET "utf8" COLLATE "utf8_unicode_ci";
This just changes the default character set / collation for each table. To convert them, you need:
ALTER TABLE tablename CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;
home_run is an implementation of ruby’s Date/DateTime classes in C, with much better performance (20-200x) than the version in the standard library, while being almost completely compatible.
Ancestry is a gem/plugin that allows the records of a Ruby on Rails ActiveRecord model to be organised as a tree structure (or hierarchy). It uses a single, intuitively formatted database column, using a variation on the materialised path pattern. It exposes all the standard tree structure relations (ancestors, parent, root, children, siblings, descendants) and all of them can be fetched in a single sql query. Additional features are STI support, named_scopes, depth caching, depth constraints, easy migration from older plugins/gems, integrit...
This may be awkward to set up, but will work once you're done.
Fun facts:
STOP SLAVE; RESET SLAVE;
and reset your my.cnf) and restart the MySQL daemon.Create replication user
: In the MySQL shell:
CREATE USER 'replicator'@'%' IDENTI...
Unless all MySQL server defaults are set to UTF-8, mysqldump encodes UTF-8 characters incorrectly and only outputs correct UTF-8 when you switch to Latin 1 (!). Also you need to setup charset and collation manually for each new database.
To prevent this, make sure your /etc/mysql/my.cnf
looks like this:
[mysqld]
default-character-set = utf8mb4
collation-server = utf8mb4_unicode_ci
[mysql]
default-character-set=utf8mb4
After that do
sudo /etc/init.d/mysql restart
To test concurrent code, you will need to run multiple threads. Unfortunately, when you use blocking system calls (e.g. locks on the database), Ruby 1.8 threads won't work because system calls will block the whole interpreter.
Luckily you can use processes instead. fork
spins off a new process, IO.pipe
sends messages between processes, Process.exit!
kills the current process. You will need to take care of ActiveRecord database connections.
Here is a full-fledged example:
describe Lock, '.acquire' do
before :each do
...
sudo gem install parallel
script/plugin install git://github.com/grosser/parallel_tests.git
config/database.yml
test:
database: xxx_test<%= ENV['TEST_ENV_NUMBER'] %>
script/dbconsole -p
CREATE DATABASE `xxx_test2`;
...
script/generate rspec
(you'll probably only let it overwrite files in script/
)
Prepare test databases...
This is about converting Haml to ERB and not the other way round which you probably want!
This process can not be automated 100%, but you can still save time.
First do
script/plugin install http://github.com/cgoddard/haml2erb.git
Then in the console type
hamls = Dir["app/views/**/*.haml"] - ['app/views/layouts/screen.html.haml'];
hamls.each do |haml|
puts haml
erb = haml.sub(/\.haml$/, '.erb')
File.open(erb, 'w') do |file|
file.write Haml2Erb.convert(File.read(haml))
end
end
After th...
sudo gem install zip
git clone git://github.com/rtomayko/date-performance.git
cd date-performance
rake package:build
cd dist
sudo gem install --no-ri --no-rdoc date-performance-0.4.7.gem
ActsAsSolr::Post.execute(Solr::Request::Delete.new(:query => "#{Location.solr_configuration[:type_field]}:#{ModelClass}"))
ActsAsSolr::Post.execute(Solr::Request::Commit.new)
This can happen during development when classes without automatic reloading are pointing to classes with automatic reloading. E.g. some class in lib
is calling Model.static_method
.
Stop referencing autoloaded classes from static files. If you can't, see workaround B and C.
Make sure the offending file (the one referencing the autoloaded class) is autoloaded, too. You may do this:
# config/application.rb
config.paths.add 'offending/file/parent/directory', eager_load: true