Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-9 of 9 total  RSS 

Save db data to fixture files

rake db:fixtures:dump_all
он сохранит все данные из ваших таблиц development базы в ямлы для тестов rake

db:fixtures:dump_references
["areas","countries"]
сохранит только те таблицы которы епрописаны у него в конфиге, в данном случае это

namespace :db do
  namespace :fixtures do

    desc 'Create YAML test fixtures from data in an existing database.
Defaults to development database. Set RAILS_ENV to override.'
    task :dump_all => :environment do
      sql = "SELECT * FROM %s"
      skip_tables = ["schema_info"]
      ActiveRecord::Base.establish_connection(:development)
      (ActiveRecord::Base.connection.tables - skip_tables).each do |table_name|
        i = "000"
        File.open("#{RAILS_ROOT}/test/fixtures/#{table_name}.yml", 'w') do |file|
          data = ActiveRecord::Base.connection.select_all(sql % table_name)
          file.write data.inject({}) { |hash, record|
            hash["#{table_name}_#{i.succ!}"] = record
            hash
          }.to_yaml
        end
      end
    end
  end
  
  namespace :fixtures do
    desc 'Create YAML test fixtures for references. Defaults to development database. 
    Set RAILS_ENV to override.'
    task :dump_references => :environment do
      sql = "SELECT * FROM %s"
      dump_tables = ["areas","countries"]
      ActiveRecord::Base.establish_connection(:development)
      dump_tables.each do |table_name|
        i = "000"
        file_name = "#{RAILS_ROOT}/test/fixtures/#{table_name}.yml"
        p "Fixture save for table #{table_name} to #{file_name}"
        File.open(file_name, 'w') do |file|
          data = ActiveRecord::Base.connection.select_all(sql % table_name)
          file.write data.inject({}) { |hash, record|
            hash["#{table_name}_#{i.succ!}"] = record
            hash
          }.to_yaml
        end
      end
    end
  end
end 

DRYing up YAML fixtures

// Rails Recipes explained how to DRY up the database configuration code. I applied the same idea to user fixtures, which worked while we used MySQL. Once on Postgres, "defaults" started throwing an error. The easiest solution was to make quentin's values the 'defaults'

quentin: &defaults
  id: 1
  login: quentin
  email: quentin@example.com
  site_id: 1
  salt: 7e3041ebc2fc05a40c60028e2c4901a81035d3cd
  crypted_password: 00742970dc9e6319f8019fd54864d3ea740f04b1 # test
  created_at: <%= 5.days.ago.to_s :db %>
  activated_at: <%= 5.days.ago.to_s :db %> # only if you're activating new signups
aaron:
  id: 2
  login: aaron
  email: aaron@example.com
  activation_code: aaronscode
  site_id: 1
  <<: *defaults
#etc...

Create YAML test fixtures from database in Rails

As found at http://media.pragprog.com/titles/fr_rr/code/CreateFixturesFromLiveData/lib/tasks/extract_fixtures.rake

desc 'Create YAML test fixtures from data in an existing database.  
Defaults to development database.  Set RAILS_ENV to override.'

task :extract_fixtures => :environment do
  sql  = "SELECT * FROM %s"
  skip_tables = ["schema_info"]
  ActiveRecord::Base.establish_connection
  (ActiveRecord::Base.connection.tables - skip_tables).each do |table_name|
    i = "000"
    File.open("#{RAILS_ROOT}/test/fixtures/#{table_name}.yml", 'w') do |file|
      data = ActiveRecord::Base.connection.select_all(sql % table_name)
      file.write data.inject({}) { |hash, record|
        hash["#{table_name}_#{i.succ!}"] = record
        hash
      }.to_yaml
    end
  end
end

Accessing Subversion repository information in Ruby

require 'yaml'
svn_info = YAML.load(`svn info /my/working/copy`)
puts svn_info['URL']
#=> "svn://some-remote-repository.com/svn"
puts svn_info['Revision']
#=> "133"


Should also work with svk info as well. Credit to htonl in #caboose for the YAML tip.

FileMetaData: simple generic file_info metadata comment

This is a general-purpose default text snippet that
you can use to add metadata to any file. It is based
on YAML.
### begin_: file metadata
    ### <region-file_info>
    ### main:
    ###   - name : ___filename___
    ###     desc : |
    ###         ___description___
    ###     date : created="___date___"
    ###     last : lastmod="___last___"
    ###     lang : ___lang___
    ###     tags : ___tags___
    ### </region-file_info>

quickly testing yaml syntax

irb --simple-prompt -r yaml
>> d = YAML.load <<-TEXT
line_with_breaks: >
  My name is Simon 
  Things I like:
    * drawings
TEXT
=> {"line_with_breaks"=>"My name is Simon Things I like:\n  * drawings\n"}


ripped from noradio

App level configuration for your Rails apps

Hard coding stuff into your view templates isn't a great idea, and sometimes you want it out of your layouts too. If you have variables your app requires, but which may change between deployments, put them in /config/appconfig.yml in YAML format, then put this at the top of your /config/environment.rb:

require 'yaml'


And at the bottom of your /config/environment.rb:

APP_CONFIG = YAML::load(File.open("#{RAILS_ROOT}/config/appconfig.yml"))


Now your YAML variables are accessible anywhere from your controllers or views like so:

APP_CONFIG["variable"]


Easy peasy.

Check that database.yml is parsed properly

You can confirm that your database YAML file is being parsed properly with this one line shell command.

ruby -ryaml -e "File.open('config/database.yml') { |f| puts YAML.load(f).inspect }"

Loading and parsing YAML files

I use YAML heavily to specify basic configuration options for my applications. Additionally, I have bash scripts to download and parse currency and weather information, which all gets stored as YAML for ease of use.

This is how I parse the YAML into my applications:

require 'yaml'

class ApplicationController < ActionController::Base
  before_filter :configure_app

  # Your code here...

  def configure_app
    @config = YAML::load(File.open("#{RAILS_ROOT}/config/config.yml"))
  end
end
« Newer Snippets
Older Snippets »
Showing 1-9 of 9 total  RSS