Coder Social home page Coder Social logo

couchrest'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's People

Contributors

candlerb avatar chrisdurtschi avatar deepj avatar dgraham avatar ellneal avatar erickt avatar ferrous26 avatar frasertweedale avatar gbuesing avatar igal avatar janraasch avatar jchris avatar jo avatar joelnb avatar kirel avatar kowsik avatar mattetti avatar ndarilek avatar samlown avatar sauy7 avatar sporkd avatar tapajos avatar tc avatar timanglade avatar topfunky avatar viniciusteles avatar wasnotrice avatar wildchild avatar will avatar yohei 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

couchrest's Issues

Bulk save of extended docs with timestamps! does not save created_at or updated_at fields

When a model is created that extends Couchrest::ExtendedDocument and it has the 'timestamps!' property in the model it is expected that a 'created_at' and 'updated_at' timestamp field will be created when the document is saved. It should not matter if the document was saved singly or using the bulk save mechanism.

This only works as expected when docs are created and saved singly. Bulk document saves do not create the expected fields.

Please find an example of this at : http://pastie.org/652473

The example first shows creating and saving an individual doc with timestamps created properly. The second part shows creating multiple docs and bulk saving them with no timestamps created after save.

Class of result after a find.

I'm new to Ruby and have been having a play with Padrino and CouchRest.

I don't know whether you can help. i think I have the latest gems installed; and I've using CouchDB 0.10.0. I have a GET method that attempts to use the CouchDB GET ID URL to return a single document. The CouchDB GET seems to work, but Padrino (or perhaps Rack) returns a

!! Unexpected error while processing request: undefined method `bytesize' for ["botanic_name", "A Tree"]:Array

The Padrino GET looks like this:

get :show, :with => :id, :map => "/species" do
sp = Species.find(params[:id])
end

Any idea where I should go to find an solution. Thanks for any help you can provide.

CouchRest database per subdomain

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

Thanks,
Shenouda Bertel

Extended::Document.save(true) is buggy

Extended::Document#save_without_callbacks gets called every time I save
that then calls database.save_doc
which will return {"ok" => true} if we are under the bulk_save_cache_limit
if we are over it, it will return bulk_save
bulk_save just returns the output of CouchRest.post "#{@root}/_bulk_docs", {:docs => docs}
which is never going to be {"ok" => true}

monkeypatch for Net::BufferedIO for 1.8 should rescue EAGAIN as well

couchrest/monkeypatches.rb replaces rbuf_fill but it seems not compatible with 1.9's one.

cf. http://jira.codehaus.org/browse/JRUBY-5075

IO#read_nonblock can raise any error defined in read(2) system call. And POSIX.1-2001 allows either error of EAGAIN and EWOULDBLOCK to be returned from read(2), and also allows both error value are not the same.

So, couchrest should rescue EAGAIN as well as EWROULDBLOCK for portability I think. Windows is a platform that has different error value for EAGAIN and EWOULDBLOCK so mswin32 CRuby must raise the same error for couchrest.

Default attribute guards assume Ruby boolean semantics

The default guard that gets put around a View in an ExtendedDocument checks that the value of doc[attribute] is true. However, JavaScript does not operate like Ruby. For instance, 0 is a false value.

Instead, they should check that "doc[attribute] != null".

bulk_save to CouchDB throws 415 Unsupported Media Type error

Hi,

When I try to bulk_save docs to CouchDB, it throws a 415 Unsupported Media Type error. This also happens when I use curl!!

I asked in the couchdb user list and Randall Leeds asked me to set the Content Type http header in the curl command. It works as expected then. That conv can be found here: http://www.listware.net/201007/couchdb-user/93016-posting-to-bulkdocs-throws-unsupported-media-type-error.html

Perhaps the way bulk_docs works has changed in CouchDB 1.0!!!! Though I dont see it documented anywhere.

thanks,
mano

Standalone Attachment API

it would be nice if couchrest supported the standalone attachment API.
Would help people get arround the Base64 encoding which bloats up documents

replicate_to seem to be broken

replicate_to causes a RestClient::InternalServerError: Internal Server Error.

In the replicate_to method invoking other_db.root returns a value like "127.0.0.1:5984/database_name", this causes an error. But, when the value is prefixed with "http://" it passes.

bug: attachments encoded multiple times

hi,

in attempting to implement a versioning gem that builds on top of couchrest_model, i discovered the following problem with couchrest: saving a document with inline attachments multiple times without a reload will cause repeated base64 encodings of the attachment data (i.e., a base64 encoding of something that's already been base64 encoded).

steps to reproduce:

open irb. create a doc with an inline attachment. save it. change a property. save it again. your attachment has now been base64 encoded twice.

Not always appropriately defining the object's name

Let's guess I have two models :

def Foo < CouchRest::ExtendedDocument
end

def Bar < CouchRest::ExtendedDocument
end

For some reason, I do :

Bar.get 'document_id'

But 'document_id' is not a Bar. It's a Foo !
So we could expect to have a Foo object and it's methods. Instead of that, we have a Bar object.

So it seems that to create the object, CouchRest relies on the class we call it with.
Would it be possible to see to return the appropriate object, based on the couchrest-type attribute?

Use document_type instead of couchrest-type by default

Documents should not know about "driver" and store odd fields like couchrest-type. IIRC it was already discussed several months ago, but unfortunately I can not find a thread. The idea:

  • Use document_type field name by default
  • Use global ExtendedDocument.set_inheritance_field "couchrest-type" for legacy
  • Use ExtendedDocument.set_inheritance_field in any class

My fork http://github.com/wildchild/couchrest/commits/document_type

Related ticket: http://jchris.lighthouseapp.com/projects/17807/tickets/22-lets-use-couchrest_type

Thoughts?

CouchRest::ExtendedDocument doesn't allow chaining the inherit class callback

CouchRest::ExtendedDocument overrides inherited() on class level without calling super(). When trying to mix an extended document with ActiveSupport's class inheritable attributes it becomes clear that the inherited() callbacks up the chain doesn't get called.

A simple patch along with a test is provided here : http://gist.github.com/246669

Have to note that running the spec along with the rest of the suite fails due to ActiveSupport's greediness with JSON encoding. Running the spec on its own shows the patch works.

Any suggestions for a cleaner, non-ActiveSupport dependent spec would be appreciated.

Avoid put requests to _design docs when accessing views

CouchDB's security module allows to explicitly define who can update _design docs on a db level.
Consider a db which grants public access to its views but just allows admin users to modify or create _design docs --> current couchrest wouldn't be able to show the pubic views as by default every db request triggers a put request to the _design docs and thus would end in an error.

SystemStackError: stack level too deep

With:

json gem 1.4.3
couchrest 0.37
rails 3 beta 2
Ruby 1.8.7 Mac OS 10.6
Couchdb 0.12.0a2c10462-git

I get the following error when the model is accessed the first time with for example Post.all

http://pastie.org/956935

If I do another Post.all then it works and I get a list of Posts.

If I downgrade the json gem to 1.2.4 this problem goes away. I've not tried other versions of this gem.

how to - Document attachments

Hello,

Thanks for the couchrest component. I'm a little lost on how to get started. I have been trying to make the steps on the couch db definitive guide manual happen with Ruby (no patience for curl after a certain point).

I think you need a forum or mailing list for non-issues like this. I also think a few dumb-examples would save EVERYONE a ton or time.

I made CouchDB save a JPG attachment with couchrest. Using this simple sequence.

rsp  = db.save_doc(  req )
doc  = db.get( rsp[ 'id' ] )
  #-- add an attachment
rslt = doc.put_attachment( 'cover', './artowrk.jpg', { } )
puts 'attachment: ', rslt

ONE

All good. Futon shows I have an attachment in the db a-OK. When I look at the 'owner' document, in this case the document is not up-to-date.

puts "doc = ", doc.inspect

With the new attachment. /Clearly/ doesn't see that the attachment is added to himself.

Like I say, I dunno if this is an 'issue' or no. To me OO-design says if you update an object via an instance method that object-instance /ought/ to reflect the changes. When that is not happening; before OO programming we used to call them: "side effects".

Personally, I say it is a philosophical point. I also say that it is an IMPORTANT point. Unfortunately, I haven't got myself into extended documents yet; at this time, I say a method on a class should maintain Class Integrity.

For example; if we don't want to refresh when I add an attachment:

       doc.put_attachment(...)

... The easy thing is to mark as invalid. The best thing is to update 'him' to reflect changes attended to by adding an attachment.

TWO

The attachment save to couchdb isn't tagged as JPG. I know that's my doing (or lack of action).

Since there's no documentation on was to do that, might we get a hint or two; say some basic parameters on the <doc.put_attachment(...)> like MIME/TYPE or make that kind of method, Protected; such that newbies like me can't use it non-appropriately. ??

That is all ...

Will.

include_docs=true not honored with class proxy and no use_database

if extended document has no use_database, and class proxy is used with Document.on(db), include_docs doesn't work.

query to Couchdb is made with include_docs, but CouchRest goes to fetch each doc anyway because the first call failed (no db set).

fix is in github.com/refractalize/couchrest

Documentation cries for improvement

The module is acceptable, your documentation is plain crap. Take attachments for example. A data field is expected to be a "newline-less" base64 encoded string. Obviously this a CouchDB specific requirement and has nothing to do with JSON. So don't you need to think that it's worth to document that "couchrest" handles this automatically and, if tomorrow CouchDB decided to rename that field into "foobar", your code will not work at all?

Large attachments fail with timeout error

When I try to attach a 50MB file on a slow server (small EC2 instance), I get this error:

RestClient::RequestTimeout: Request Timeout
from /home/deploy/.bundle/ruby/1.8/gems/rest-client-1.5.1/lib/restclient/request.rb:147:in `transmit'
from /home/deploy/.bundle/ruby/1.8/gems/rest-client-1.5.1/lib/restclient/request.rb:56:in `execute'
from /home/deploy/.bundle/ruby/1.8/gems/rest-client-1.5.1/lib/restclient/request.rb:31:in `execute'
from /home/deploy/.bundle/ruby/1.8/gems/rest-client-1.5.1/lib/restclient.rb:76:in `put'
from /home/deploy/.bundle/ruby/1.8/gems/couchrest-0.37/lib/couchrest/core/adapters/restclient.rb:21:in `put'
from /home/deploy/.bundle/ruby/1.8/gems/couchrest-0.37/lib/couchrest/core/rest_api.rb:6:in `put'
from /home/deploy/.bundle/ruby/1.8/gems/couchrest-0.37/lib/couchrest/core/database.rb:176:in `save_doc'
from /home/deploy/.bundle/ruby/1.8/gems/couchrest-0.37/lib/couchrest/more/extended_document.rb:244:in `save_without_callbacks'
from /home/deploy/.bundle/ruby/1.8/gems/couchrest-0.37/lib/couchrest/more/extended_document.rb:218:in `update'
from /home/deploy/.bundle/ruby/1.8/gems/couchrest-0.37/lib/couchrest/mixins/callbacks.rb:413:in `_run_save_callbacks'
from /home/deploy/.bundle/ruby/1.8/gems/couchrest-0.37/lib/couchrest/more/extended_document.rb:217:in `update'
from /home/deploy/.bundle/ruby/1.8/gems/couchrest-0.37/lib/couchrest/mixins/callbacks.rb:403:in `_run_update_callbacks'
from /home/deploy/.bundle/ruby/1.8/gems/couchrest-0.37/lib/couchrest/more/extended_document.rb:216:in `update'
from /home/deploy/.bundle/ruby/1.8/gems/couchrest-0.37/lib/couchrest/more/extended_document.rb:212:in `catch'
from /home/deploy/.bundle/ruby/1.8/gems/couchrest-0.37/lib/couchrest/more/extended_document.rb:212:in `update'
from /home/deploy/.bundle/ruby/1.8/gems/couchrest-0.37/lib/couchrest/more/extended_document.rb:234:in `save'
from /home/deploy/.bundle/ruby/1.8/gems/couchrest-0.37/lib/couchrest/more/extended_document.rb:228:in `catch'
from /home/deploy/.bundle/ruby/1.8/gems/couchrest-0.37/lib/couchrest/more/extended_document.rb:228:in `save'
from /home/deploy/.bundle/ruby/1.8/gems/couchrest-0.37/lib/couchrest/more/extended_document.rb:252:in `save!'

This monkeypatch fixes the problem (albeit inelegantly):

module RestClient
  def self.put(url, payload, headers={}, &block)
    RestClient::Request.execute(
      :method => :put,
      :url => url,
      :payload => payload,
      :headers => headers,
      :timeout => 300, &block)
  end
end

First question: why does it take so long? It appears the default timeout is about 60 seconds. Uploading the same attachment with curl takes about 8 seconds. The timeout starts after CouchRest does its Base64 encoding (which takes about 14 seconds), so that's not the issue.

Second question: is there a better way to extend the timeout? Ideally, this would be intelligent--ie. if the payload is bigger, allow a longer timeout, as it seems that time scales geometrically with the size of the attachment.

Request timeout problem

Hello,

I'm testing couchrest on a rails application with no much success so far, i've created my application structure using the scaffold functionality without much trouble but when i try to access it i get a "Request Timeout" error i've digged the code around and i've changed the timeout manually (to 1000) on the file "/var/lib/gems/1.8/gems/rest-client-1.6.1/lib/restclient/request.rb" just for the pourpouse of testing and i get a "RestClient::ServerBrokeConnection" error.
I found that i'm getting this error when couchrest tries to insert the javascript code of a view that shows all the elements of the database. I copied the view's code and inserted it using both curl and futon without any problem or delay in response.

¿can somebody give a hint on can i solve this problem?

thanks

Restart test causes multiple failures on CouchDB 1.0

The "CouchDB should restart" test causes lots of collateral test failures when using 1.0.0 if it fails.

The as written test throws a "RestClient::ServerBrokeConnection" error when the "restart" command is issued. I'm not sure this is entirely unexpected.

Catching this error and then continuing makes the test pass, as well as the other tests.

it "should restart" do
    begin
      @cr.restart!
    rescue RestClient::ServerBrokeConnection
       # this is expected, I suppose
    end

    begin
      @cr.info
    rescue
       # Give the couchdb time to restart
       sleep 0.2
     retry
     end
end

Casting with Integers and .dup

Hi, I'm casting a model (Money class) whose to_json method is the following:

def to_json(opts = {})
   cents.to_s
end

This gets stored in CouchDB as an integer value. Trying to load the base object afterwards fails as there is a .dup call made on the integer representation. The culprit is line 110 in mixins/properties.rb:

def convert_property_value(property, klass, value)
   ......
     klass.send(property.init_method, value.dup)
   ...
end

Removing the .dup resolves the problem and the tests still seem to pass okay. Is there a specific reason the .dup is there? If not, can it be removed?

Sam

Conflict handling

Test that RestClient::Conflict is passed through (or something CouchRest specific) so that it can be properly handled.

This should also be documented.

Parse method in CouchRest breaks remote db replication

I believe I've found a bug where, depending on how you use couchrest to create your database(s), remote db replication is either successful or errors out.

It appears to me that the parse(url) method in CouchRest ignores the scheme from the uri when
using CouchRest.database!('http//server/db'). If I'm reading the couchrest specs for parsing urls correctly, they explicitly test for the removal of the scheme.

The bug, showing up as RestClient::InternalServerError, is that the uri scheme is required in the payload RestClient posts to couchdb when replicating from a remote couchdb e.g.,
RestClient.post('127.0.0.1/_replicate', { "source":"http://server/db", "target":"db-replica" }) # => works
RestClient.post('127.0.0.1/_replicate', { "source":"server/db", "target":"db-replica" }) # => error

This bug is sidestepped by explicitly running:

cr = CouchRest.new('http://server')
cr.create_db('db')

as the parse method is not called. As far as I can see, this is how the specs for replication are constructed.

As a sidenote, I noticed that the couchrest replication functions don't support continuous replication.

I have a suggested patch.

Error with simple test

#!/bin/ruby
require 'couchrest'
require 'pp'
require 'json'


DB = CouchRest.database!("http://localhost:5984/test_service")
class Service < CouchRest::ExtendedDocument
  use_database DB

  view_by :name
  view_by :host
  view_by :type

  property :name
  property :host
  property :type

end



[ [ "MySQL Master", "a0.aprico.central", "mysql_master"],
  [ "MySQL Slave", "a1.aprico.central", "mysql_master"],
  [ "MySQL Slave", "a2.aprico.central", "mysql_master"],
  [ "App Server", "a3.aprico.central", "app_server"],
  [ "App Server", "a4.aprico.central", "app_server"],

  [ "App Server", "a5.aprico.central", "app_server"]
].each do |r|
  s = Service.new :name => r[0], :host => r[1], :type => r[3]
  s.save
end

require 'pp'
results = Service.by_name 
puts results.count

generates the error

/usr/lib/ruby/gems/1.8/gems/rest-client-1.3.1/lib/restclient/mixin/response.rb:44:in `return!': Internal Server Error (RestClient::InternalServerError)
from /usr/lib/ruby/gems/1.8/gems/rest-client-1.3.1/lib/restclient/request.rb:223:in `process_result'
from /usr/lib/ruby/gems/1.8/gems/rest-client-1.3.1/lib/restclient/request.rb:160:in `transmit'
from /usr/lib/ruby/1.8/net/http.rb:543:in `start'
from /usr/lib/ruby/gems/1.8/gems/rest-client-1.3.1/lib/restclient/request.rb:157:in `transmit'
from /usr/lib/ruby/gems/1.8/gems/rest-client-1.3.1/lib/restclient/request.rb:66:in `execute_inner'
from /usr/lib/ruby/gems/1.8/gems/rest-client-1.3.1/lib/restclient/request.rb:54:in `execute'
from /usr/lib/ruby/gems/1.8/gems/rest-client-1.3.1/lib/restclient/request.rb:31:in `execute'
from /usr/lib/ruby/gems/1.8/gems/rest-client-1.3.1/lib/restclient.rb:68:in `get'
from /usr/lib/ruby/gems/1.8/gems/couchrest-0.34/lib/couchrest/core/adapters/restclient.rb:13:in `get'
from /usr/lib/ruby/gems/1.8/gems/couchrest-0.34/lib/couchrest/core/rest_api.rb:18:in `get'
from /usr/lib/ruby/gems/1.8/gems/couchrest-0.34/lib/couchrest/core/database.rb:81:in `view'
from /usr/lib/ruby/gems/1.8/gems/couchrest-0.34/lib/couchrest/more/../mixins/collection.rb:155:in `load_target'
from /usr/lib/ruby/gems/1.8/gems/couchrest-0.34/lib/couchrest/more/../mixins/collection.rb:144:in `method_missing'
from test.rb:37

my gem list is

aws-s3 (0.6.2)
builder (2.1.2)
bundler (0.9.6)
cgi_multipart_eof_fix (2.5.0)
chef (0.7.16)
chef-server (0.7.16)
coderay (0.9.1)
columnize (0.3.1)
couchrest (0.34)
cucumber (0.6.2)
cucumber-nagios (0.6.7)
daemons (1.0.10)
diff-lcs (1.1.2)
eventmachine (0.12.10)
extlib (0.9.14)
fastthread (1.0.7)
ferret (0.11.6)
gem_plugin (0.2.3)
gemcutter (0.3.0)
git (1.2.5)
haml (2.2.17)
highline (1.5.2)
hoe (2.5.0)
jashmenn-git-style-binaries (0.1.10)
jeweler (1.4.0)
json_pure (1.2.0)
linecache (0.43)
merb-assets (1.0.15)
merb-core (1.0.15)
merb-haml (1.0.15)
merb-helpers (1.0.15)
mime-types (1.16)
mixlib-log (1.1.0)
mongrel (1.1.5)
mysql (2.8.1)
polyglot (0.3.0)
poolparty (1.4.8)
prawn (0.6.3)
prawn-core (0.6.3)
prawn-format (0.2.3)
prawn-layout (0.3.2)
prawn-security (0.1.1)
rack (1.1.0)
rake (0.8.7)
rest-client (1.3.1)
right_aws (1.10.0)
rspec (1.3.0)
ruby-debug (0.10.3)
ruby-debug-base (0.10.3)
rubyforge (2.0.3)
s33p (0.0.0)
stompserver (0.9.9)
syntax (1.0.0)
SystemTimer (1.1.3)
templater (1.0.0)
term-ansicolor (1.0.4)
thor (0.9.9)
treetop (1.4.3)
wirble (0.1.3)
xml-simple (1.0.12)

brad@bradgonesurfing:~/workspace/couchdb$couchdb -V

couchdb - Apache CouchDB 0.8.0-incubating

keep-alive connections

Hello.
My rake task makes over 1000 requests(db.view('uri-here')) to the database.
I get an error "getaddrinfo name or service not known".
When I have inspected the script using strace I found that this error raised because too much files(socket = file in unix) were open.
And when the script shutting down(I catch all exceptions) strace is showing me "close" methods of all created sockets.
I have tried to execute GC.start but this didn't make me any profit.
Is it possible to use keep-alive connections with couchrest?

Validations are buggy

Code:


class Crap < CouchRest::ExtendedDocument
  include CouchRest::Validation
  use_database CouchDB.default_database

  property :fail

  before_save :check_something

  private
    def check_something
      self.errors.add(:fail, "You're bastard")
    end
end

Output from console:



> crap = Crap.new
> => {"couchrest-type"=>"Crap"}
> 
> > crap.fail = 'something'
> > => "something"
> > crap.valid?
> > => true
> > crap.save
> > => true
> > crap.errors
> > => #["You're bastard"]}>
> > crap.valid?
> > => true
> 
> 

ExtendedDocument shouldn't failed on nil value in argument

ActiveRecord supports to use nil value in its argument when creating (without saving) a new model. If I use the same way with CouchRest the calling is failed on error.

I think it should return a blank model and not fail on it. I need to change it because Devise uses this calling when building a resource for a session in my Rails app.

http://github.com/plataformatec/devise/blob/master/lib/devise/controllers/helpers.rb#L91

Here is my patch
http://github.com/deepj/couchrest/commit/099f9ba25bf4eefdef16d4eb07e701a2488e1497

User creation

Is user creation something that would be considered in scope for this library? E.g.:

def self.create_user_doc(username, password, roles = [])
  doc = {
    :name => username,
    :_id => "org.couchdb.user:" + username,
    :type => "user",
    :roles => (roles || [])
  }
  if !password.nil?
    doc[:salt] = UUID.generate
    doc[:password_sha] = Digest::SHA1.hexdigest(password + doc[:salt])
  end
  return doc
end

_design/[Document] revision would be updated every-time database is accessed

i have a CouchRest::ExtendedDocument of this form

module modd
class device < CouchRest::ExtendedDocument
attr_accessor :device_id
property :device_id

view_by :device_id

end
end

on the database a design document would be stored as "_design/modd::device", its revision will be updated on every access to the database even for simple query like device.all.count

i've tried putting the class outside of the module and it works fine, "_design/device" doesn't get updated on every access to the database

How do you use list functions

I have a _design document with a list function. I would like to use it via CouchRest, but I am not sure how to do that.

Is this built into CouchRest?

HEAD requests aka .exist?

It would be nice if couchrest supported an .exist?() call for documents
This could be done using a head request.
The ETag will contain the _rev if it does exist.

STI Equivalent

Hello,

Has anyone already thought of starting to work on something similar to active record's single table inheritance ?

Let's guess two classes :

class User < CouchRest::ExtendedDocument
end

class Admin < User
end

Currently, couchrest wouldn't see that the admin is in fact a user. We couldn't retrieve all users (admins included).

The idea would be, when a class inherits from an other, to add an attribute "couchrest-sti", which would have the subclass value.
When we do a User.all, it's retrieve all the objects having "couchrest-type" defined to user.
But if it has a "couchrest-sti" defined, it'd instantiate the object as the class defined in that attribute. Not as a user.

I really need this. So I'd be willing to work on it. But is it something you'd find useful and that'd have a chance to get implemented to the trunk ?

Ruby 1.8.6 issues warning to parenthesize arguments for abstract_response.rb

I wish I knew how to submit a patch but I'm pretty weak in git. When running a ruby file with a single line:

require("couchrest")

I get the warning:
C:/apps/ruby/lib/ruby/gems/1.8/gems/rest-client-1.6.1/lib/restclient/abstract_re
sponse.rb:50: warning: parenthesize argument(s) for future version

I find that changing line 50 of that file to this eliminates the warning (and I believe does not change the intended function):
raise RequestFailed(self)

I hope this is helpful - contact me if you need additional info.

Steve

ExtendedDocument views don't return documents with database set

I'm not using the use_database(db) command in my ExtendedDocuments (just because I don't like globals that much). So I use :database => @db when accessing my views, but the ExtendedDocuments that are returned don't have their 'database' set, so I can't save or destroy them.

I have a patch if you want it, although I've only been using couchrest for a couple of days so I'm probably missing something...

Document uses extlib_inheritable_accessor, which dup's the database

This seems like a bad idea. If I have several ExtendedDocuments, they all have references to separate CouchRest::Database instances. If I change one, it doesn't reflect across the others.

I'm trying to write an Sinatra app which scopes different clients to different databases. Since every subclass of CouchRest::ExtendedDocument comes with a separate copy of the database, it's impossible to change all of them at once.

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.