Giter Site home page Giter Site logo

couchrest_model's Introduction

CouchRest: CouchDB, close to the metal

Build Status

CouchRest wraps CouchDB's HTTP API using persistent connections with the HTTPClient gem managing servers, databases, and JSON document serialization using CouchDB's API endpoints so you don't have to.

CouchRest is designed to provide a simple base for application and framework-specific object oriented APIs. CouchRest is Object-Mapper agnostic, the JSON objects provided by CouchDB are parsed and returned as Document objects providing a simple Hash-like interface.

For more complete modelling support based on ActiveModel, please checkout CouchRest's sister project: CouchRest Model.

CouchDB Version

Tested on latest stable release (1.6.X), but should work on older versions above 1.0. Also known to work on Cloudant.

Performance with Persistent Connections

When connecting to a CouchDB 1.X server from a Linux system, you may see a big drop in performance due to the change in library to HTTPClient using persistent connections. The issue is caused by the NOWAIT TCP configuration option causing sockets to hang as they wait for more information. The fix is a simple configuration change:

curl -X PUT "http://localhost:5984/_config/httpd/socket_options" -d '"[{nodelay, true}]"'

Install

$ sudo gem install couchrest

Basic Usage

Getting started with CouchRest is easy. You can send requests directly to a URL using a RestClient-like interface:

CouchRest.put("http://localhost:5984/testdb/doc", 'name' => 'test', 'date' => Date.current)

Or use the lean server and database orientated API to take advantage of persistent and reusable connections:

server = CouchRest.new           # assumes localhost by default!
db = server.database!('testdb')  # create db if it doesn't already exist

# Save a document, with ID
db.save_doc('_id' => 'doc', 'name' => 'test', 'date' => Date.current)

# Fetch doc
doc = db.get('doc')
doc.inspect # #<CouchRest::Document _id: "doc", _rev: "1-defa304b36f9b3ef3ed606cc45d02fe2", name: "test", date: "2015-07-13">

# Delete
db.delete_doc(doc)

Running the Specs

The most complete documentation is the spec/ directory. To validate your CouchRest install, from the project root directory use bundler to install the dependencies and then run the tests:

$ bundle install
$ bundle exec rake

To date, the couchrest specs have been shown to run on:

  • MRI Ruby 1.9.3 and later
  • JRuby 1.7.19
  • Rubinius 2.5.7

See the Travis Build status for more details.

Docs

Changes history: history.txt

API: http://rdoc.info/projects/couchrest/couchrest

Check the wiki for documentation and examples http://wiki.github.com/couchrest/couchrest

Contact

Please post bugs, suggestions and patches to the bug tracker at http://github.com/couchrest/couchrest/issues.

Follow us on Twitter: http://twitter.com/couchrest

Also, check https://twitter.com/search?q=couchrest

couchrest_model's People

Contributors

candlerb avatar crx avatar daddye avatar dpzaba avatar ellneal avatar estei avatar gbuesing avatar gsterndale avatar igal avatar igauravsehrawat avatar jchris avatar jonmchan avatar kirel avatar kostia avatar mattetti avatar moonmaster9000 avatar ndarilek avatar pacoguzman avatar pezra avatar samlown avatar sauy7 avatar sobakasu avatar sporkd avatar tapajos avatar topfunky avatar viniciusteles avatar wasnotrice avatar weppos avatar wildchild avatar will avatar

Stargazers

 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  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  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  avatar  avatar  avatar  avatar  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

couchrest_model's Issues

New model instances are identical

Maybe I'm going crazy, but this shouldn't be happening right?

.new should always return a new instance of an object
It seems to me that it's always pointing to the same instance of an object.

Simple Example:

class User < CouchRest::Model::Base
     property :name
     property :permissions, :default => []

     def add_default_permission
          self.permissions.push('something')
     end
end

User.new == User.new # => true
User.new(:name => 'user1') == User.new(:name => 'user2') # => false
User.new(:name => 'user') == User.new(:name => 'user') # => true

I think this could be related to the other issue I raised #63
There's something going wrong with the way couchrest_model is instantiating objects

Calling add_default_permission method on new instances,highlights the issue further

user1 = User.new
user1.add_default_permission

puts user1 # => {:name => nil, :permissions => ['something']}

user2 = User.new
user2.add_default_permission

puts user2 # => {:name => nil, :permissions => ['something','something']}

couchrest_model 1.1

Is possible to release a 1.1 version (soon) without erubis ~> 2.6 dependency?

Thanks so much!

Performance slowdown between beta7 and beta8

Hi,

I've been using beta7 for a while now (custom built to fix the incorrect encoding on the published version of the gem) without any issue.

For a new project I linked to the git repository for couchrest_model to be completely up-to-date, but have noticed a sharp decrease in performance when querying for documents.

I have a model 'Event' which doesn't contain a huge amount of data (8 fields all short strings of text). With 100 documents of this type pre-filled into my database, my rails app running beta7 takes ~125ms to get them all and render them.

Using beta8 (latest github code), this is over 1000ms.

What do I need to provide to help diagnose this issue? I can put a sample Rails app up if that helps? I'm happy to try and dig around and figure out what might be causing the problem, but might need to be pointed in the right direction!

proxy_database with use_database

Dears,

kindly, i have a question about proxy in couchrest_model :
why to set use_database in the main entity model while there is the proxy_database that will be used as the database of that model ... required to be by default.

Model#by_foo doesn't work

class Document < CouchRest::Model::Base
  property :foo_id, String
  view_by :foo_id
end

Document.by_foo_id "fooooo"

# TypeError: can't convert Symbol into String
#   from /Users/weppos/.rvm/gems/ruby-1.8.7-p330/gems/couchrest_model-1.0.0/lib/couchrest/model/views.rb:96:in `delete'
#   from /Users/weppos/.rvm/gems/ruby-1.8.7-p330/gems/couchrest_model-1.0.0/lib/couchrest/model/views.rb:96:in `view'
#   from /Users/weppos/.rvm/gems/ruby-1.8.7-p330/gems/couchrest_model-1.0.0/lib/couchrest/model/base.rb:63:in `method_missing'
#   from (irb):17

It seems that the method_missing generates the following statement

Document.view(:by_foo_id, "fooooo")

while it should be

Document.view(:by_foo_id, :key => "fooooo")

model instance giving false when it should be true

I'm comparing two instances of a User model which are the same document.
One version is loaded by couchrest_model from a belongs_to relationship the other is in the session originally loaded by a view

example:
@exam.user == @session[:user] => false

yet

@exam.user.id == @session[:user].id => true

This appears to be couch specific behaviour, i have tested with an activerecord active_model example using sqlite3, which gives me the behaviour I'd expect.

Anyone know why this would be?
activemodel 3.0.3
couchrest 1.0.1
couchrest_model @ 83b70e

When inspected both objects are the same
putting the following in a simple Ruby script writes out true

   hash1 = {
      "system_admin"=>false,
      "name"=>"Rob Aldred",
      "login_at"=>"Mon, 28 Mar 2011 16:42:00 +0100",
      "created_at"=>"Fri Jan 28 13:24:17 +0000 2011",
      "_rev"=>"11-30a39268d60ea8163b15e2dc1a5d032a",
      "question_admin"=>false,
      "reset_password"=>nil,
      "updated_at"=>"Mon Mar 28 16:42:00 +0100 2011",
      "_id"=>"bb5d83ba347f2aaff54aabdf18ff95bb",
      "test_admin"=>false,
      "role_ids"=>["e4b407a538c45913b2835e8c677656bd"],
      "password_salt"=>"urIBww0s",
      "couchrest-type"=>"User",
      "deactivated"=>false,
      "user_admin"=>false,
      "password_hash"=>"ba6917a6a184ac3cec04e9e2f55861029a9bad4a1941555ed8dd924010561e72",
      "email"=>"[email protected]"
    }

hash2 = {
      "system_admin"=>false,
      "name"=>"Rob Aldred",
      "login_at"=>"Mon, 28 Mar 2011 16:42:00 +0100",
      "created_at"=>"Fri Jan 28 13:24:17 +0000 2011",
      "question_admin"=>false,
      "_rev"=>"11-30a39268d60ea8163b15e2dc1a5d032a",
      "reset_password"=>nil,
      "updated_at"=>"Mon Mar 28 16:42:00 +0100 2011",
      "test_admin"=>false,
      "_id"=>"bb5d83ba347f2aaff54aabdf18ff95bb",
      "role_ids"=>["e4b407a538c45913b2835e8c677656bd"],
      "password_salt"=>"urIBww0s",
      "couchrest-type"=>"User",
      "deactivated"=>false,
      "user_admin"=>false,
      "password_hash"=>"ba6917a6a184ac3cec04e9e2f55861029a9bad4a1941555ed8dd924010561e72",
      "email"=>"[email protected]"
    }

puts hash1 == hash2

Casted Model and Rails

Dear,

how my Casted Model "< Hash" works with rails.
as i got "undefined method `new' for #CouchRest::Model::CastedArray:0xaac05f8"
when calling new method.

Time parse issue

Hi,

I'm using to git version of couchrest_model, and suppose the Time.mktime_with_offset() method in typecast.rb is the replace of the default "Time.parse()". But looks like it not working as promised:

            Loading development environment (Rails 3.0.3)
            ruby-1.9.2-rc2 :001 > Time.now.zone
             => "CST" 
            ruby-1.9.2-rc2 :002 > Time.now
             => 2011-01-18 20:15:38 +0800 
            ruby-1.9.2-rc2 :003 > Time.parse(Time.now.to_s)
             => 2011-01-18 20:15:52 +0800 
            ruby-1.9.2-rc2 :004 > Time.mktime_with_offset(Time.now.to_s)
             => 2011-01-18 06:16:10 +0800 
            ruby-1.9.2-rc2 :005 > Time.zone_offset("CST")
             => -21600

Assigning a CastedHash to a property declared as a Hash assigns an empty hash instead

class Foo < CouchRest::Model::Base
  property :bar, Hash
end

foo = Foo.new
# => {"model"=>"Foo", "bar"=>nil} 
foo.bar = {'hello' => 'world'}
# => {"hello"=>"world"} 
foo.bar
# => {"hello"=>"world"} 
foo.bar = foo.bar
# => {"hello"=>"world"} 
foo.bar
# => {}

After assigning to the "bar" property, calling foo.bar returns a CouchRest::Model::CastedHash. This is from CouchRest::Model::Property#cast:

elsif (type == Object || type == Hash) && (value.class == Hash)
  # allow casted_by calls to be passed up chain by wrapping in CastedHash
  CastedHash[value, self, parent]
elsif !value.nil?
  cast_value(parent, value)
end

On the second assignment, since value.class is CouchRest::Model::CastedHash instead of Hash, this ends up calling typecast_value, which returns Hash.new because value.instance_of?(Hash) is false.

datetime_select stores all the parts as well as the combined value

Hey,

When using a datetime_select helper for a model, the combined value is stored correctly, but the individual parts are also stored:

"subscription_start_date": "2010/06/30 11:46:11 +0000",
"subscription_start_date(1i)": "2010",
"subscription_start_date(2i)": "6",
"subscription_start_date(3i)": "30",
"subscription_start_date(4i)": "12",
"subscription_start_date(5i)": "46"

(I'm BST, so I guess that is why there is the 1h discrepancy).

Is this something that couchrest_model (or couchrest) should handle, or something on my end?

Thanks

CouchRest database per main Entity

Dears,
i'm looking for implement in my application to have database for the main entity of the system.
i'd like to create and set a database for this entity named with a property value.

Like : For a CMS Project, to create a couchdb database for every Site.

kindly, as that is based on Rest and Rails :
in the create method i have the property value,
so i can create the database and save the document in side that database.
but in the other methods how can i specify the database to get the documents from, in (show, edit, update, delete). and in the index method, how can be enhanced for that scenario (Database per Main Entity).

also, how can i check if there a database with the value i have with creating the database if not exist.

Thanks,
Shenouda Bertel

ActiveModel::Dirty

Hey, The ActiveModel::Dirty implementation was removed in 2ee92a5
I desperately need to be able to perform validation on save so that admins cannot edit documents unless they have the draft property set to true

so my simple before_save validation method:

if draft_was == false
    errors.add(:draft, 'published documents cannot be edited')
    return false
end

without the dirty implementation I have to get messy in my controller which is not great.
Any ideas if dirty will ever be making it back into couchrest::model::base

Improve view usability

Rather than handling view options in a messy Hash, provide an object notation that allows views to be returned as objects on which requests can be made, similar to Arel in Rails3 or the Sequel library.

All requests to a view related method should return a new instance of a view that bases itself on it's parent object. This allows for chaining and re-use. The object should be capable of detecting when two incompatible options are provided, such as combining :key with :startkey.

Result sets from a view should be provided in an object notation, as opposed to an array or hash. For example, view_object.total_rows performs the view, caching the result in the object, and returns the total number of rows. Calling view_object.rows would provide the cached array of the query result. Later, calling view_object.each or view_object.all would perform the query again, but with the :include_docs option.

An initial sample design of this is being worked on:

https://github.com/samlown/couchrest_model/blob/master/lib/couchrest/model/view.rb

Coupled with this, the current notation of view_by :name which creates views called 'by_name', is not suitable for all situations. It should be updated so that calling view :updated creates a view called 'updated' and must include the :map option. This may cause some backwards incompatibility as the view class method is currently used for manual queries.

Any thoughts or ideas would be much appreciated!
sam

Proxy Class and Persistence and Validation

Dears,

the proxy is not supported by Persistence class and Validation Class as every class doesn't have validation for proxy and if the database is not declared in the model by use_database and error raise "Database missing for design document refresh" from design_doc class
because the self.class for these classes with in proxy return the Model it self not the ProxyClass.

Regards,
Shenouda Bertel

Dependency on “activesupport ~> 2.3.5”

A few commits changed the dependencies, and between adding the model generator (24th August) and a merge (24th August), the dependency on ActiveSupport was removed. However, couchrest_model on rubygems (v1.0.0.0.beta8) still list activesupport ~> 2.3.5 as a dependency — perhaps this ought to be updated? :)

PS: For people looking for a solution, slap this onto your Gemfile:
gem 'couchrest_model', '~> 1', :git => 'git://github.com/couchrest/couchrest_model.git', :ref => 'c32992c21'

defining/using as_json with options doesn't work properly

I am using a to_json/as_json type interaction with a couchrest_model class, and passing the :only => ["_id"] option into it, I would assume I would only get json objects with _id attributes, instead I get that + a bunch of attribute defaults that come with a model that I don't care about.

This feels like a bug, its just the hash signature of a "new" version of this couchrest_model object.

Any advice?

Conflict in project that utilizes ActiveRecord on CouchRest Model

Note: This may be due to a bug in Rails 3.

When using the CouchRest Model gem in a project that already uses ActiveRecord 3.0.0, various errors occur when running model specs when lib/couchrest/railtie.rb is in the load path.

It seems that line 7 in lib/couchrest/railtie.rb:

config.generators.orm :couchrest_model

Causes Rails to completely disable ActiveRecord, instead of only using couchrest_model as the ORM for generators!

Argument Error Raised Calling Reduced View

I just upgraded my rails 3 site to use couchrest_model to take advantage of the active model goodness and for the most part things work as expected. Now I can get rid of my hacked together active_model compliant couchrest extended document. Thanks!

I did however run into a problem:

I have a view in my model that worked perfectly with couchrest extended document, but doesn't work any longer with couchrest model.

The view just emits a complex key and then 1 and I have a reduce function that sums up the view.

When I call the view in my controller like this:

@closed = Trade.by_system(:key => [@system.id, "Closed"], :descending => true)

Extended Document would automatically have this call the non-reduced view unless you specified :reduce => true.

So, I thought to myself, well why don't I just call :reduce => false, but that didn't work either.

The long story short is that views with reduce functions can only be accessed with :reduce => true and there is no way to get the non reduced output any more. I get an argument error when trying to call the non reduced version.

Unless I am missing something, I think this is a bug.

Bundling From Git
Rails 3.0.0
Latest Couchrest Gem

Handling CouchDB Doc inside other Doc

Dears,

kindly, i was looking for handle CouchDB Doc inside CouchDB Doc with CastedModel as below:

class CatToy < Hash
include CouchRest::Model::CastedModel

property :name, String
property :purchased, Date
end

class Cat < CouchRest::Model::Base
property :name, String
property :toy, CatToy
end

@cat = Cat.new(:name => 'Felix', :toy => {:name => 'mouse', :purchases => 1.month.ago})
@cat.toy.class == CatToy
@cat.toy.name == 'mouse'

which provide the below JSON Document :

{
"name":"Felix",
"toy" : {
"name" : "mouse",
"purcahse": "2010-10-08",
"couchrest-type": "CatToy"},
"couchrest-type": "Cat"
}

which is a supported document structure for CouchDB.
and when i apply that with Hash CastedModel i got the below exception :
"An array inside an array cannot be casted, use CastedModel"

please, advice.

Database missing

Dears,

i got when trying couchrest_model master with rails master :
Database missing for design document refresh
and how can i configure the database used with the model.

it will help if sharing a rails3 application using couchrest_model capabilities and features.

Basic testing with RSpec2 - assigns usage

I recently put a question in SO before checking here.
http://stackoverflow.com/questions/6163316/testing-errors-in-rails-with-couchrest-model-using-rspec

I cannot find much documentation about the use of RSpec or testing in general with CouchRest Model.

What I noticed is that in my tests they fail because the order of elements in the hash is not the same.

Failure/Error: assigns(:projects).should eq([@project])

   expected [{"name"=>"test", 
              "updated_at"=>2011-05-28 11:24:04 -0500,
              "created_at"=>2011-05-28 11:24:04 -0500, 
              "couchrest-type"=>"Project",
              "_id"=>"709edbfaafb24fa1eff7d5f3966b2bda",
              "_rev"=>"1-ae3f6356f8e32f6006337a4f3759bca4"}]
        got [{"name"=>"test",
              "updated_at"=>2011-05-28 11:24:04 -0500, 
              "created_at"=>2011-05-28 11:24:04 -0500,
              "_id"=>"709edbfaafb24fa1eff7d5f3966b2bda",
              "_rev"=>"1-ae3f6356f8e32f6006337a4f3759bca4",
              "couchrest-type"=>"Project"}]

I wonder why for the same document we could have different order of the properties inside the hash?
Any idea?

Rails3 generators crash

I have installed the couchrest_model gem and now my generators are failing, just typing "rails g" fails.

I tried the following but it did not help:

application.rb

config.generators do |g|
g.orm :active_record
g.template_engine :erb
g.test_framework :rspec, :fixture => false
end

Pagination in 1.1.0b5

Strange thing. I was using Item.by_sku.paginate to paginate my catalog, but after updating to 1.1.0b5 i got this error:

ruby-1.9.2-p180 :004 > Item.by_sku.paginate
NoMethodError: undefined method `paginate' for #<Array:0x00000104b8eb88>

ruby-1.9.2-p180 :012 > Article.paginate(:page => 1, :per_page => 2, :design_doc => 'Article', :view_name => 'by_date')
NoMethodError: undefined method `[]' for nil:NilClass
from /Users/andoriyu/.rvm/gems/ruby-1.9.2-p180@ngein/bundler/gems/couchrest_model-fcd9e2ba8e0f/lib/couchrest/model/persistence.rb:113:in `build_from_database'

timestamps! generating wrong timezone format

I'm working on a project with couchrest_model and couchdb-lucene where I need to sort the search by the updated_at attribute. Couchdb-lucene is complaining it cannot parse the updated_at attribute.

After some research, I found that SimpleDateFormat class used in couchdb-lucene expects the timezone to be 4digits without the colon separating hour from minutes as defined in RFC 822. So, instead of 2011-02-20T09:15:37-06:00 it should be 2011-02-20T09:15:37-0600.

This string is generated in the typecast.rb file in the mktime_with_offset method.

I'd appreciate if you could look into this.

Thanks,

Leonardo Almeida

Proxyable didn't support model namespace

Dears,

as per the new upcoming release of rails 3.1 which support model name space which generated with the scaffold.
also my couchrest generator in my respiratory support that kind of generating modules and model namespace @ http://github.com/shenoudab/couchrest_model

but the proxyable functionality of couchrest_model doesn't support the mode namespace for proxy_for
as when trying to set the class_name for a proxy_for property to "Admin::Post"

i got that error :

undefined method `model_proxy=' for {"doc_type"=>"Admin::Post"}:Admin::Post

Best Regards,
Shenouda Bertel

to_json :except => ['senstive_field'] not working for CouchRest Model

I was trying to build a very common User model with a simple password. In a controller, I need a json output of user info, so I tried to override to_json on the model. But it didn't work - it just diligently show the password field!

class User < CouchRest::Model::Base 
  def to_json
    super(:except => [:password])
  end

  property :first_name,  String
  property :last_name, String
  property :email,  String
  property :phone,  String
  property :since,  DateTime
  property :password, String
  property :address, Address

  timestamps!

  design do
    view :by_first_name
    view :by_since
    view :by_email
  end

  def full_name 
    self.first_name + self.last_name
  end

end

Feature Request: create_from_database even when :include_docs => false

Hi,

Not sure how clear this will be, but hopefully this makes sense.

Imagine we're in ActiveRecord, and you have a Cat ActiveRecord model. Cat's may have several properties (:name, :sex, :color, etc.). You know how in ActiveRecord, you can do a Cat.find :all, :select => [:name] and get back an array of Cat objects with populated name properties, but with all the other properties null?

Well, a similar thing to do with CouchDB/CouchRest::Model is to create a view with a map like the following:
view_by :just_name, :map => "function(doc){emit(doc.id, {'name': doc.name})}"

Then you could do a Cat.by_just_name :include_docs => false - except that doesn't do what you'd expect. Instead of taking the value results in the view and trying to run them through Cat.create_from_database, so that you end up with an array of Cat objects, you get the raw CouchDB response.

I understand why - the values in a view could be anything. But wouldn't it be great if there was an option like :load_values => true that would run the view value results through create_from_database and give you back an array of Cat objects?

Let me know what you think.

Thanks!

Reduce view called with :keys => [key1, key2, ...]

Hi,

I'm trying to call a view using an array of keys and then reduce that view but I am getting a 400 Bad Request error.

my view call looks like this:

ClassName.by_field_and_length(:keys => keys, :reduce => true, :group => true)

If I call it with just :keys, it works fine. I can set :include_docs => false, but I'd be much happier doing a reduce on the CouchDB side.

Is this possible? If so, is there a problem with couchrest_model that is preventing me from doing this?

controller spec using rspec2 which mocks a CouchRest::Model is not populating "assigns" properly.

I have a Product < CouchRest::Model::Base, a generated products_controller and corresponding spec. I have mocked Product.all to return a list of a mock Product model.

The controller assigns "@products" to be a list of this mock model as expected, but upon return (in the spec) assigns(:products) is [{}](a list containing one ActiveSupport::HashWithIndifferentAccess)

If I change Product to inherit from ActiveRecord::Base, the mocking works as expected (assings(:products) is a list containing the mock Product instance).

In products_controller
def index

  @products = Product.all
  debugger # HERE @products == [ <my mock product, as I expect>]       
  respond_to do |format|
    format.html # index.html.erb
  end
end

In spec/controllers/products_controller_spec
def mock_product(stubs={})
(@mock_product ||= mock_model(Product).as_null_object).tap do |product|
product.stub(:to_hash => {:id => 1}) #for some reason, with active_couch 'to_hash' needs to be explicit in order to evaluate url helpers like 'products_path'
product.stub(stubs) unless stubs.empty?
end
end

describe "GET index" do
  it "assigns all products as @products" do
    Product.should_receive(:all).and_return([mock_product])
    get :index
    debugger # HERE assigns(:products) is a list with an empty ActiveSupport::HashWithIndifferentAccess
    assigns(:products).should eq([mock_product])
  end
end

Casted Models Defaults

Dears,

i tried to set defaults for a casted model as follow :

class Cat < CouchRest::Model::Base
property :name, String
property :toy, CatToy, :default => {:name => 'car', :type => "Transports"}
end

class CatToy < Hash
include CouchRest::Model::CastedModel

property :name, String
property :purchased, Date
property :type, String
end

the above structure for setting defaults for the casted model doesn't work, is there any other ways or any suggested way to do so.

Thanks,
Shenouda Bertel

Casted Models with anonymous classes

Hi,

I'm following the tutorial we have attached here to create a casted model with anonymous class but the code doesn't work. Even tho' the code knows that there are two elements, their values don't appear inside the array. Is it related to the version I'm running, in this case 1.0.1?
=> {"rating"=>nil, "name"=>"Felix", "toys"=>[{}, {}], "couchrest-type"=>"Cat"}

Thanks a lot,
Alberto

CastedModel#update_attributes calls save

Calling update_attributes on a CastedModel results in a call to #save inside #update_attributes which doesn't exist in a CastedModel.

The solution is either to create a stub save method or change update_attributes to not call save if save is not present.

Attaching a new document corrupts all previous attachments

How to reproduce

class Document < CouchRest::Model::Base
  property :name
end

d = Document.create(:name => "hello")

d.create_attachment(:name => "v1", :file => StringIO.new("Hello #{Time.now.to_i.to_s}"), :content_type => "text/plain")
d.save!

d.create_attachment(:name => "v2", :file => StringIO.new("Hello #{Time.now.to_i.to_s}"), :content_type => "text/plain")
d.save!

d.create_attachment(:name => "v3", :file => StringIO.new("Hello #{Time.now.to_i.to_s}"), :content_type => "text/plain")
d.save!

When you attach a new document, all the previous documents become unreadable. The content is replaced into a string like aGVsbG8KCg==.

validation on castedmodel

class Order < CouchRest::Model::Base
  property :title
  property :label
  property :customer, Customer
  validates_presence_of :title,:label,:customer
end

class Customer < Hash
  include CouchRest::Model::CastedModel
  property :name
  property :address
  validates_presence_of :name,:address
end

order = Order.new
order.valid? 
#=> false
order.errors
=> #<OrderedHash {
    # :label=>["can't be blank"], 
    # :customer=>["can't be blank"], 
    # :title=>["can't be blank"]}> 

order.customer
=>  nil
customer = Customer.new
=>  {"address"=>nil, "name"=>nil}
customer.valid?    
=>  false

customer.errors
=> #<OrderedHash {:address=>["can't be blank"], :name=>["can't be blank"]}> 

order.customer = customer
=> {"address"=>nil, "name"=>nil}

order.valid?
=> false

order.errors

=> #<OrderedHash {
    # :label=>["can't be blank"], 
    # :customer=>["translation missing: en, activemodel, errors, models, order, attributes, customer, invalid"],
   # :title=>["can't be blank"]}> 


   :customer=>["translation missing: en, activemodel, errors, models, order, attributes, customer, invalid"]

Am I doing something wrong?

Bug in Operators or Methods

This issue is related to issues #67, #63, #80 and #47.
I have tried with couchrest_model versions '1.0.0' and '1.1.0.beta5'.

Earlier I reported issue #80 when I couldn't make RSpec tests pass.

Assuming a model:

class Project < CouchRest::Model::Base
  property :name,   String
  timestamps!
  view_by :name
end

If you execute this (p = Project.create) != Project.find(p.id) it will result true which is incorrect because it is supposed to be the same object!

In detail:

p = Project.create(:name => "Oryx")
q = Project.find(p.id)
p == q  #=> false

p.inspect
 => "{\"name\"=>\"Oryx\", \"updated_at\"=>2011-05-31 20:11:31 UTC, \"created_at\"=>2011-05-31 20:11:31 UTC, \"type\"=>\"Project\", \"_id\"=>\"fca58f2f95d0a2676be34ee534452e85\", \"_rev\"=>\"1-4321807631f65320890b8b08bbf225c9\"}"

q.inspect
 => "{\"name\"=>\"Oryx\", \"updated_at\"=>2011-05-31 20:11:31 UTC, \"created_at\"=>2011-05-31 20:11:31 UTC, \"_id\"=>\"fca58f2f95d0a2676be34ee534452e85\", \"_rev\"=>\"1-4321807631f65320890b8b08bbf225c9\", \"type\"=>\"Project\"}"

Which is exactly the problem I found in my testing using RSpec in issue #80.

Reference:

rspec/rspec-rails#386

Why to remove the `id` property on destroy?

Hi, in the destroy method, the code goes like this:

def destroy
  _run_destroy_callbacks do
    result = database.delete_doc(self)
    if result['ok']
      self.delete('_rev')
      self.delete('_id')
    end
    result['ok']
  end
end

Is there any real reason you remove _rev and _id? Only because of the hypothetical "preparing ... to be saved to a new _id"? Why not just set @destroyed=false and freeze the object?

There's a real issue with removing the _id property here:
crx/tire@abf491d#commitcomment-414706

#attributes= refuses to store not-defined properties

Here's an example code.

class Journal < CouchRest::Model::Base
  property :action, String
end

j = Journal.new({ :action => "hello", :custom => "value" })
j.save!
# => { :action => "hello", :custom => "value" }

j = Journal.new
j.attributes = { :action => "hello", :custom => "value" }
j.save!
# => { :action => "hello" }

My model doesn't define a :custom property. However, if I pass the property through new, the final object will contain that property.
When the same property is passed via #attributes, the value is ignored and never stored on the server.

Because CouchDB is a schemaless database, I believe CouchRest should not force you to define all properties in advance.

Also, is there any reason why CouchRest doesn't allow to set custom values on the fly? Again, CouchDB is a schemaless database, why CouchRest wants me to define all properties in advance?

class Journal < CouchRest::Model::Base
  property :action, String
end

j = Journal.new({ :action => "hello", :custom => "value" })
# fails
j.write_attribute("other", "value")
# fails
j["other"] = "value"
j.save!

uniqueness encoding urf-8

Dears,

in the uniqueness class the first line of encoding must be changed from "urf-8" to "utf-8".

thanks,
Shenouda Bertel

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.