Git Product home page Git Product logo

sprig-reap's Introduction

Sprig::Reap

Gem Version Code Climate Circle CI

Don't want to write Sprig seed files from scratch? No problem! Sprig::Reap can create them for you. Sprig::Reap enables automatic capture and output of your application's data state to Sprig-formatted seed files.

Installation

# Command Line
gem install sprig-reap

# Gemfile
gem 'sprig-reap'

Usage

Via a rake task:

rake db:seed:reap

Or from the Rails console:

Sprig.reap

By default, Sprig::Reap will create seed files (currently in .yaml only) for every model in your Rails application. The seed files will be placed in a folder in db/seeds named after the current Rails.env.

If any of the models in your application are using STI, Sprig::Reap will create a single seed file named after the STI base model. STI sub-type records will all be written to that file.

Additional Configuration

Don't like the defaults when reaping Sprig::Reap records? Change 'em!

Target Environment

You may specify the target environment (db/seeds target folder):

# Rake Task
rake db:seed:reap TARGET_ENV=integration

# Rails Console
Sprig.reap(target_env: 'integration')

Model List

If you only want to reap a subset of your models, you may provide a list of models (ActiveRecord::Base.subclasses-only) or ActiveRecord::Relations (for pulling records based on scope):

# Rake Task
rake db:seed:reap MODELS=User,Post.published

# Rails Console
Sprig.reap(models: [User, Post.published])

Ignored Attributes

If there are any ignored attributes you don't want to show up in any of the seed files, let reap know:

# Rake Task
rake db:seed:reap IGNORED_ATTRS=created_at,updated_at

# Rails Console
Sprig.reap(ignored_attrs: [:created_at, :updated_at])

Omitting Empty Attributes

If you have models with lots of attributes that could potentially be nil/empty, the resulting seed files could get cluttered with all the nil values. Remove them from your seed files with:

# Rake Task
rake db:seed:reap OMIT_EMPTY_ATTRS=true

# Rails Console
Sprig.reap(omit_empty_attrs: true)

Combine Them All!

You're free to take or leave as many options as you'd like:

# Rake Task
rake db:seed:reap TARGET_ENV=integration MODELS=User,Post.published IGNORED_ATTRS=created_at,updated_at OMIT_EMPTY_ATTRS=true

# Rails Console
Sprig.reap(target_env: 'integration', models: [User, Post.published], ignored_attrs: [:created_at, :updated_at], omit_empty_attrs: true)

Adding to Existing Seed Files (.yaml only)

Already have some seed files set up? No worries! Sprig::Reap will detect existing seed files and append to them with the records from your database with no extra work needed. Sprig::Reap will automatically assign unique sprig_ids so you won't have to deal with pesky duplicates.

NOTE: Sprig::Reap does not account for your application or database validations. If you reap seed files from your database multiple times in a row without deleting the previous seed files or sprig records, you'll end up with duplicate sprig records (but they'll all have unique sprig_ids). This may cause validation issues when you seed your database.

License

This project rocks and uses MIT-LICENSE.


Code At Viget

Visit code.viget.com to see more projects from Viget.

sprig-reap's People

Contributors

bramswenson avatar dholdren avatar h0tl33t avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

sprig-reap's Issues

sprig-reap won't write to file ?

rake db:seed:reap MODELS=Space --verbose
D, [2014-11-24T16:21:01.516395 #18380] DEBUG -- : Reaping records from the database...
  Space Load (25.8ms)  SELECT "spaces".* FROM "spaces"
uninitialized constant Sprig::Reap::FileAttribute::CarrierWave issue writing to the file for Space:
D, [2014-11-24T16:21:02.279273 #18380] DEBUG -- : Finished reaping!

How to load generated yml-files for habtm associations with sprig?

Sprig-Reap created also yml-files for habtm-association-tables like this example below. But Sprig requires in seeds.rb to specify a classname. So what's the benefit of having this generated files? How can I use them meaningfully?

records:

  • sprig_id:
    package_id: 1
    station_id: "<%= sprig_record(PayTv::Station, 1).id %>"
  • sprig_id:
    package_id: 2
    station_id: "<%= sprig_record(PayTv::Station, 1).id %>"

Side effects with pg_search gem

When using the gem pg_search spring-reap will fail with

ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR:  relation "pg_search_documents" does not exist
LINE 1: SELECT "pg_search_documents".* FROM "pg_search_documents"
                                            ^
: SELECT "pg_search_documents".* FROM "pg_search_documents"
-e:1:in `<main>'
Tasks: TOP => db:seed:reap

So, in general it would be nice if standard errors would be skipped and in summary will be shown what couldn't be serialized.

Spring creates the pg_search_documents.yml although the exception was thrown so it would be also useful if the empty file wouldn't be created or at least removed if it is empty.

Thank you for your work! ๐Ÿ‘

undefined method `fetch' for false:FalseClasserProfile: AND no implicit conversion of nil into Stringr UserProfile:

When I reap simple tables with no associations it seems to work fine, for example if I reap ONLY User and Community, individually, or together.

However, when I try to reap User, Community, AND UserProfile I consistently get one of the following two errors (depending upon what subset of the data I try to reap):

no implicit conversion of nil into Stringr UserProfile:
(possible clue: that extra 'r' after the word String?)
or
undefined methodfetch' for false:FalseClasserProfile:`

the UserProfile table has 2 'parent' tables:
belongs_to :user
accepts_nested_attributes_for :user
belongs_to :community
accepts_nested_attributes_for :community
(User has_one :user_profile, and COmmunity has_many :user_profiles)

Even when I define a method self.for_seed_db which is so specific it selects a single User and UserProfile, and run

rake db:seed:reap TARGET_ENV=development MODELS=UserProfile.for_seed_db,User.for_seed_db,Community

I get the error no implicit conversion of nil into Stringr UserProfile:
but it correctly reaps the single User and the set of Communities.

Adding OMIT_EMPTY_ATTRS=true doesn't help.

Any thoughts what could prevent a specific table from being reaped and giving either of those two errors?

Rails 3.2.21, ruby 2.1.5, running on a Mac.

Document that sprig-reap supports AR relations

As far as I can tell from reviewing the code and writing some additional tests, sprig-reap supports supplying AR relations for the list of models to reap, and then only reaping models returned by those relations. Is there any reason this isn't called out in the documentation? Is this just a coincidence of implementation that my not be supported going forward, or a true feature? If the latter, perhaps some documentation can be added to the README noting as much?

does sprig-reap work with latest ruby/rails?

Hi, I was previously running both sprig and sprig-reap OK but lately I am getting errors even when trying to do the simplest reap task. The only thing I can think of is that perhaps before I was using a different version of ruby and/or rails. My current version of ruby is 2.2.0 and rails 4.2.0.

Right now if I run rake db:seed:reap it quickly shows "Finished reaping!" but doesn't create any files although there's definitely data in the database. And if I try and specify options and say limit to just my User model I get the following nil error. Other models throw errors as well and it almost feels like the errors occur because I require many of my models to be linked to a user record (i.e. user_id cannot be null).

`rake db:seed:reap TARGET_ENV=development MODELS=User

D, [2015-03-18T06:10:57.471191 #86792] DEBUG -- : Reaping records from the database...
rake aborted!
NoMethodError: undefined method -' for nil:NilClass /Users/dude/.rvm/gems/ruby-2.2.0@tigerwod/gems/sprig-reap-0.2.0/lib/sprig/reap/tsortable_hash.rb:20:inblock (2 levels) in resolve_circular_habtm_dependencies!'`

It would be nice if sprig-reap could recognise associations

It would be phantastic if reap would be able to automatically set relations (ie ancestry: '<%= sprig_record(Qbrick::Page, 1).id %>') which are already in other yaml files.

While active records supports association reflections which enable to aggregate information about the relation attributes this could be realistic and would be a really great feature.

EDIT:
Hu? This seems to work sometimes? Is it dependent from the relation?

EDIT 2:
But in my cases the used sprig class was the wrong one. ๐Ÿ˜ฟ

sprig-reap broke the yaml formatting

I already hat a sprig definition with the structure

options:
  find_existing_by: ['identifier']

records:
  - sprig_id: 1
    identifier: lorem
  - sprig_id: 2
    identifier: ipsum

After using sprig-reap the structure was

options:
  find_existing_by: ['identifier']

records:
  - sprig_id: 1
    identifier: lorem
  - sprig_id: 2
    identifier: ipsum

- sprig_id: 3
  identifier: dolor
- sprig_id: 3
  identifier: sit

So there was wrong indention (the duplicated id is already mentioned in another issue)

Isolated namespace

I have a dummy development app inside which there are bunch of engines with isolated namespaces.
All my models are using this namespace. Let's say "Dummy".

Reap, whilst not reporting any issues, is not generating any files as it doesn't find any models.
If i specifically say something like
rake db:seed:reap MODELS=Dummy::Model
it generates yml just fine.

Is there any way to define a namespace globally?
Or at list to say something like MODELS=Dummy::*

Haven't tried yet Sprig itself, but i suppose i'll have problems there too?

CarrierWave uploader breaks data dump

OS X 10.7 - Rails 4.0.3, ruby 2.1.1p76 using PostgreSQL.
My Rails app. uses either ActsAsTaggableOn and Carrierwave. Every user has a Post and an Avatar uploaded via carrierwave on S3. Dumping all the user in a users.yml seed file works fine but the script explodes in my face with:

ArgumentError: undefined class/module Struct::AvatarUploader

The strange thing is that when i run for the first time

bundle exec rake db:seed:reap TARGET_ENV=development MODELS=User,Post IGNORED_ATTRS=created_at,updated_at

I don't get any error. I start receiving the error above from the second time i launch that command onward.

Here is a snatch of the users.yml file:

records:
- sprig_id: 2
  username: user2
  email: [email protected]
  encrypted_password: "$2a$10$GVFZPxh3tu2uO0mNs/D9SuihSzzsAOANZ.1J4MNGu73sUoGAYYQua"
  admin: false
  locked: false
  slug: user2
  reset_password_token: 
  reset_password_sent_at: 
  remember_created_at: 
  sign_in_count: 0
  current_sign_in_at: 
  last_sign_in_at: 
  current_sign_in_ip: 
  last_sign_in_ip: 
  confirmation_token: 
  confirmed_at: &1 2014-06-27 19:35:14.399730000 Z
  confirmation_sent_at: 
  unconfirmed_email: 
  avatar: &2 !ruby/object:AvatarUploader
    model: !ruby/object:User
      attributes:
        id: 2
        username: user2
        email: [email protected]
        encrypted_password: "$2a$10$GVFZPxh3tu2uO0mNs/D9SuihSzzsAOANZ.1J4MNGu73sUoGAYYQua"
        admin: false
        locked: false
        slug: user2
        reset_password_token: 
        reset_password_sent_at: 
        remember_created_at: 
        sign_in_count: 0
        current_sign_in_at: 
        last_sign_in_at: 
        current_sign_in_ip: 
        last_sign_in_ip: 
        confirmation_token: 
        confirmed_at: *1
        confirmation_sent_at: 
        unconfirmed_email: 
        avatar: u2.jpg
        created_at: &3 2014-06-27 19:35:14.410751000 Z
        updated_at: &4 2014-06-27 19:35:14.410751000 Z
        on_private_message: '1'
        on_post_voted: '1'
        on_post_commented: '1'
        on_post_linked: '1'
        on_post_smart_filtered: '1'
        incomplete_reminder_timing: '1'
        digest_timing: '1'
        job_title: Corporate Metrics Manager
        summary: repurpose bleeding-edge channels
    mounted_as: :avatar
    storage: !ruby/object:CarrierWave::Storage::File
      uploader: *2
    file: !ruby/object:CarrierWave::SanitizedFile
      file: "...[edited].../public/uploads/user/avatar/2/u2.jpg"
      original_filename: 
      content_type: 
    versions:
      :thumb: &5 !ruby/object:AvatarUploader::Uploader70229152586100
        model: !ruby/object:User
          attributes:
            id: 2
            username: user2
            email: [email protected]
            encrypted_password: "$2a$10$GVFZPxh3tu2uO0mNs/D9SuihSzzsAOANZ.1J4MNGu73sUoGAYYQua"
            admin: false
            locked: false
            slug: user2
            reset_password_token: 
            reset_password_sent_at: 
            remember_created_at: 
            sign_in_count: 0
            current_sign_in_at: 
            last_sign_in_at: 
            current_sign_in_ip: 
            last_sign_in_ip: 
            confirmation_token: 
            confirmed_at: *1
            confirmation_sent_at: 
            unconfirmed_email: 
            avatar: u2.jpg
            created_at: *3
            updated_at: *4
            on_private_message: '1'
            on_post_voted: '1'
            on_post_commented: '1'
            on_post_linked: '1'
            on_post_smart_filtered: '1'
            incomplete_reminder_timing: '1'
            digest_timing: '1'
            job_title: Corporate Metrics Manager
            summary: repurpose bleeding-edge channels
        mounted_as: :avatar
        storage: !ruby/object:CarrierWave::Storage::File
          uploader: *5
        file: !ruby/object:CarrierWave::SanitizedFile
          file: "...[edited].../public/uploads/user/avatar/2/thumb_u2.jpg"
          original_filename: 
          content_type: 
        versions: {}
  on_private_message: '1'
  on_post_voted: '1'
  on_post_commented: '1'
  on_post_linked: '1'
  on_post_smart_filtered: '1'
  incomplete_reminder_timing: '1'
  digest_timing: '1'
  job_title: Corporate Metrics Manager
  summary: repurpose bleeding-edge channels

Any clue, hint help is appreciated.

Tests won't pass on ruby 2.1.x

Working on #16 I found an issue using ruby 2.1.2. Yaml files are parsed differently from 1.9.x so loading some fixtures has quoting issues.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.