Search Results

Search found 67 results on 3 pages for 'randombits'.

Page 1/3 | 1 2 3  | Next Page >

  • Ruby on Rails: models that do not have a table

    - by randombits
    What's the best way to create a model in Ruby on Rails that doesn't have an underlying implementation in as far as a database table goes? It's very common to write classes that perform behavior on a particular problem domain, yet can use some of the benefits that ActiveRecord has such as validation. Is it best to just create it as a module or helper? What is the best practice here?

    Read the article

  • Memory efficient way of inserting an array of objects with Core Data

    - by randombits
    I'm working on a piece of code for an iPhone application that fetches a bunch of data from a server and builds objects from it on the client. It ends up creating roughly 40,000 objects. They aren't displayed to the user, I just need to create instances of NSManagedObject and store them to persistent storage. Am I wrong in thinking that the only way to do this is to create a single object, then save the context? is it best to create the objects all at once, then somehow save them to the context after they're created and stored in some set or array? If so, can one show some example code for how this is done or point me in the direction to code where this is done? The objects themselves are relatively straight forward models with string or integer attributes and don't contain any complex relationships.

    Read the article

  • Ruby on Rails: Using XML Builder Partials

    - by randombits
    Partials in XML builder are proving to be non-trivial. After some initial Google searching, I found the following to work, although it's not 100% xml.foo do xml.id(foo.id) xml.created_at(foo.created_at) xml.last_updated(foo.updated_at) foo.bars.each do |bar| xml << render(:partial => 'bar/_bar', :locals => { :bar => bar }) end end this will do the trick, except the XML output is not properly indented. the output looks something similar to: <foo> <id>1</id> <created_at>sometime</created_at> <last_updated>sometime</last_updated> <bar> ... </bar> <bar> ... </bar> </foo> The <bar> element should align underneath the <last_updated> element, it is a child of <foo> like this: <foo> <id>1</id> <created_at>sometime</created_at> <last_updated>sometime</last_updated> <bar> ... </bar> <bar> ... </bar> </foo> Works great if I copy the content from bar/_bar.xml.builder into the template, but then things just aren't DRY.

    Read the article

  • Ruby on Rails: having two xmlbuilder templates per action , one for errors one for regular output

    - by randombits
    What's the best way to handle having two templates (or should it be one, DRY?) for xml builder templates? I'm building a web api with Rails and wanted to see an example of how to have a view that does regular output vs one that does error output. I've been using @obj.to_xml for a while, but my requirements have changed and require me building my own error templates. do you typically have both views in one with a condition above for errors such as app/views/myresource/create.xml.builder unless @myobj.errors.empty? // xml for errors here? end // regular xml view

    Read the article

  • Automated testing with Ruby on Rails - best practices

    - by randombits
    Curious, what are you folks doing in as far as automating your unit tests with ruby on rails? Do you create a script that run a rake job in cron and have it mail you results? a pre-commit hook in git? just manual invokation? I understand tests completely, but wondering what are best practices to catch errors before they happen. Let's take for granted that the tests themselves are flawless and work as they should. What's the next step to make sure they reach you with the potentially detrimental results at the right time?

    Read the article

  • iPhone: Fastest way to create a binary Plist with simple key/value strings

    - by randombits
    What's the best way to create a binary plist on the iPhone with simple string based key/value pairs? I need to create a plist with a list of recipe and ingredients. I then want to be able to read this into an NSDictionary so I can do something like NSString *ingredients = [recipes objectForKey:@"apple pie"]; I'm reading in an XML data file through an HTTP request and want to parse all of the key value pairs into the plist. The XML might look something like: <recipes> <recipe> <name>apple pie</name> <ingredients>apples and pie</ingredients> </recipe> <recipe> <name>cereal</name> <ingredients>milk and some other ingredients</ingredients> </recipe> </recipes> Ideally, I'll be able to write this to a plist at runtime, and then be able to read it and turn it into an NSDictionary later at runtime as well.

    Read the article

  • How to use NSPredicate for Key-Path values

    - by randombits
    Using an NSPredicate for an array is rather straight forward using filteredArrayUsingPredicate:. How is this done for key-path values? Meaning, I have an array of objects (in this case, the objects are of the same type). The objects each have an instance variable called name. As per the documentation, it says to do the following: NSPredicate *predicate = [NSPredicate predicateWithFormat: @"ANY employees.firstName like 'Matthew'"]; Is that -also- used in filteredArrayUsingPredicate? What if I have an array of People objects? does that mean I would use: NSArray *allPeopleObjects; // pre-populated NSPredicate *predicate = [NSPredicate predicateWithFormat:@"ANY people.name like 'Foo'"]; NSArray *matching = [allPeopleObjects filteredArrayUsingPredicate:predicate]; Documentation is a bit lacking in that department.

    Read the article

  • NSPredicate that is the equivalent of SQL's LIKE

    - by randombits
    I'm looking for a way to use NSPredicate to set a LIKE condition to fetch objects. In addition to that, an OR would be useful as well. I'm trying to do something where if a user searches "James" I can write an NSPredicate that will do the equivalent of: select * from users where firstname LIKE '%James%' OR lastname LIKE '%James%';

    Read the article

  • search and replace with ruby regex

    - by randombits
    I have a text blob field in a MySQL column that contains HTML. I have to change some of the markup, so I figured I'll do it in a ruby script. Ruby is irrelevant here, but it would be nice to see an answer with it. The markup looks like the following: <h5>foo</h5> <table> <tbody> </tbody> </table> <h5>bar</h5> <table> <tbody> </tbody> </table> <h5>meow</h5> <table> <tbody> </tbody> </table> I need to change just the first <h5>foo</h5> block of each text to <h2>something_else</h2> while leaving the rest of the string alone. Can't seem to get the proper PCRE regex, using Ruby.

    Read the article

  • Ruby on Rails 2.3.5: update_all failing on ActiveRecord

    - by randombits
    I'm trying to update a collection of records in my database using ActiveRecord's update_all. Enter script/console. MyModel.update_all("reserved = 1", :limit => 1000) ActiveRecord thinks limit is a column, says it's unknown and throws an exception. According to the documentation though, my syntax looks sane. This is RoR 2.3.5. When doing MyModel.update_all("reserved = 1") alone, it works just fine.

    Read the article

  • Ruby on Rails 2.3.5: update_all failing on ActiveRecord

    - by randombits
    I'm trying to update a collection of records in my database using ActiveRecord's update_all. Enter script/console. MyModel.update_all("reserved = 1", :order => 'rand()', :limit => 1000) ActiveRecord thinks order is a column, says it's unknown and throws an exception. According to the documentation though, my syntax looks sane. This is RoR 2.3.5. When doing MyModel.update_all("reserved = 1") alone, it works just fine. Also if I do MyModel.update_all("reserved = 1", "reserve_type = 2", :order = "rand()", :limit = 1000) = 0 0 rows affected. I'm simply trying to do: UPDATE MyModel SET reserved=1, reserve_type=2 ORDER BY RAND() LIMIT 1000

    Read the article

  • Newly installed Ruby gems not showing up in $LOAD_PATH

    - by randombits
    I'm using MacPorts in order to manage my Ruby/Rails/Gems installations. Recently after doing a gem install wirble, wirble fails to load when I start an instance of irb. Here's the output: $ irb --simple-prompt Couldn't load Wirble: no such file to load -- wirble The Wirble gem doesn't show up in my $LOAD_PATH: >> puts $: /opt/local/lib/ruby1.9/gems/1.9.1/gems/actionmailer-2.3.5/lib /opt/local/lib/ruby1.9/gems/1.9.1/gems/actionpack-2.3.5/lib /opt/local/lib/ruby1.9/gems/1.9.1/gems/activerecord-2.3.5/lib /opt/local/lib/ruby1.9/gems/1.9.1/gems/activeresource-2.3.5/lib /opt/local/lib/ruby1.9/gems/1.9.1/gems/activesupport-2.3.5/lib /opt/local/lib/ruby1.9/gems/1.9.1/gems/mysql-2.8.1/lib /opt/local/lib/ruby1.9/gems/1.9.1/gems/mysql-2.8.1/ext /opt/local/lib/ruby1.9/gems/1.9.1/gems/mysql-2.8.1/bin /opt/local/lib/ruby1.9/gems/1.9.1/gems/rack-1.0.1/bin /opt/local/lib/ruby1.9/gems/1.9.1/gems/rack-1.0.1/lib /opt/local/lib/ruby1.9/gems/1.9.1/gems/rails-2.3.5/bin /opt/local/lib/ruby1.9/gems/1.9.1/gems/rails-2.3.5/lib /opt/local/lib/ruby1.9/gems/1.9.1/gems/rake-0.8.7/bin /opt/local/lib/ruby1.9/gems/1.9.1/gems/rake-0.8.7/lib /opt/local/lib/ruby1.9/gems/1.9.1/gems/rubygems-update-1.3.7/hide_lib_for_update /opt/local/lib/ruby1.9/gems/1.9.1/gems/rubygems-update-1.3.7/bin /opt/local/lib/ruby1.9/site_ruby/1.9.1 /opt/local/lib/ruby1.9/site_ruby/1.9.1/i386-darwin10 /opt/local/lib/ruby1.9/site_ruby /opt/local/lib/ruby1.9/vendor_ruby/1.9.1 /opt/local/lib/ruby1.9/vendor_ruby/1.9.1/i386-darwin10 /opt/local/lib/ruby1.9/vendor_ruby /opt/local/lib/ruby1.9/1.9.1 /opt/local/lib/ruby1.9/1.9.1/i386-darwin10 . => nil >> The gem is definitely installed: $ gem list |grep -i wirble wirble (0.1.3) It is located in /opt/local/lib/ruby/gems/1.9.1/gems/wirble-0.1.3/ How do I get this and future gems I installed appended to my $LOAD_PATH?

    Read the article

  • Rails 2.3.x, named_scope chaining with INNER JOIN complication

    - by randombits
    I have two hypothetical classes, Foo and Bar. Foo contains many Bars. Bar can only belong to one Foo. Ultimately the SQL query I'm trying to make happen looks like the following: SELECT * from bar INNER JOIN foo ON bar.foo_id = foo.id where bar.in_use = 0 and bar.customer_id = 1 and foo.category = 0 That query does what I need. Now I'm trying to break the problem down in Rails using chained named_scopes. First, the straight forward in_use and customer_id scopes I have set: named_scope :available, :conditions => { :in_use => 0 } named_scope :not_available, :conditions => { :in_use => 1 } named_scope :customer, lambda { |num| { :conditions => { :customer_id => num } } } Now the part I'm stuck at, is I'm trying to do something like this in my code: abar = Bar.available.customer(1).category(0) how and where do I put the category named_scope to make this work?

    Read the article

  • How to quickly search an array of objects in Objective-C

    - by randombits
    Is there a way in Objective-C to search an array of objects by the contained object's properties if the properties are of type string? For instance, I have an NSArray of Person objects. Person has two properties, NSString *firstName and NSString *lastName. What's the best way to search through the array to find everyone who matches 'Ken' anywhere in the firstName OR lastName properties?

    Read the article

  • Rails choking on the content of this request because of protect_from_forgery

    - by randombits
    I'm trying to simply test my RESTful API with cURL. Using the following invocation: curl -d "name=jimmy" -H "Content-Type: application/x-www-form-urlencoded" http://127.0.0.1:3000/people.xml -i Rails is dying though: ActionController::InvalidAuthenticityToken (ActionController::InvalidAuthenticityToken): :8:in `synchronize' Looks like it's running this through a protect_from_forgery filter. I thought protect_from_forgery is excluded for non-HTML HTTP POST/PUT/DELETE type requests? This is clearly targeting the XML format. If I pass actual XML content, it works. But my users will be submitting POST data as URL encoded parameters. I know all the various ways I can disable protect_from_forgery but what's the proper way of handling this? I want to leave it on so that when I do have HTML based forms and handle format.html, I don't forget to re-enable it for then. I want users to be able to make HTTP POST requests to my XML-based API though and not get bombarded with this.

    Read the article

  • Rails 2.x http basic authentication

    - by randombits
    I'm trying to get basic http authentication working on my Rails app. I'm offering a simple REST interface served by a Rails server, only xml/json output. Every method needs authentication, so I put the authenticate filter in ApplicationController: class ApplicationController < ActionController::Base helper :all # include all helpers, all the time before_filter :authenticate protected def authenticate authenticate_or_request_with_http_basic do |u, p| true end end end Even with having the method return true, I'm receiving a 401 from the server: $ curl http://127.0.0.1:3000/myresource/1.xml -i HTTP/1.1 401 Unauthorized Cache-Control: no-cache WWW-Authenticate: Basic realm="Application" X-Runtime: 1 Content-Type: text/html; charset=utf-8 Content-Length: 27 Server: WEBrick/1.3.1 (Ruby/1.9.1/2010-01-10) Date: Thu, 03 Jun 2010 02:43:55 GMT Connection: Keep-Alive HTTP Basic: Access denied. If I'm explicitly returning true, yet getting served a 401.

    Read the article

  • Python dealing with dates and times

    - by randombits
    I'm looking for a solution to the following: Given today's date, figure out what month was before. So 2 should return for today, since it is currently March, the third month of the year. 12 should return for January. Then based on that, I need to be able to iterate through a directory and find all files that were created that month. Bonus points would include finding the most current file created for the previous month.

    Read the article

  • Ruby on Rails protect_from_forgery best practice

    - by randombits
    I'm currently working on building a RESTful web api with ruby on rails. I haven't bothered putting a proper authentication scheme into the API yet as I'm ensuring that tests and the basic behavior of the API is working all locally first. Upon testing non-HTTP GET type requests such as HTTP POST/DELETE/PUT, stuff chokes because protect_from_forgery is on by default. How does this work when I'm working in practice since essentially the idea is in a RESTful API that there is no state. The client does not have a session or a cookie associated with the server. Each request is an atomic, self-executed request. The user will supply some credentials to ensure they are who they say they are, but other than that, does protect_from_forgery make sense at this point? Should it remain enabled?

    Read the article

  • Using the groupby method in Python, example included

    - by randombits
    Trying to work with groupby so that I can group together files that were created on the same day. When I say same day in this case, I mean the dd part in mm/dd/yyyy. So if a file was created on March 1 and April 1, they should be grouped together because the "1" matches. Here's the code I have so far: #!/usr/bin/python import os import datetime from itertools import groupby def created_ymd(fn): ts = os.stat(fn).st_ctime dt = datetime.date.fromtimestamp(ts) return dt.year, dt.month, dt.day def get_files(): files = [] for f in os.listdir(os.getcwd()): if not os.path.isfile(f): continue y,m,d = created_ymd(f) files.append((f, d)) return files files = get_files() for key, group in groupby(files, lambda x: x[1]): for file in group: print "file: %s, date: %s" % (file[0], key) print " " The problem is, I get lots of files that get grouped together based on the day. But then I'll see multiple groups with the same day. Meaning I might have 4 files grouped that were created on the 17th. Later on I'll see another unique set of 2 files that are also created on the 17th. Where am I going wrong?

    Read the article

  • Ruby on Rails - differentiating plural vs singular resource in a REST API

    - by randombits
    I'm working on building the URLs for my REST API before I begin writing any code. Rails REST magic is fantastic, but I'm slightly bothered the formatting of a URL such as: http://myproject/projects/5 where Project is my resource and 5 is the project_id. I think if a user is looking to retrieve all of their projects, then a respective HTTP GET http://myproject/projects makes sense. However if they're looking to retrieve information on a singular resource, such as a project, then it makes sense to have http://myproject/project/5 vs http://myproject/projects/5. Is it best to avoid this headache, or do some of you share a similar concern and even better - have a working solution?

    Read the article

  • iPhone: Speeding up a search that's polling 17,000 Core Data objects

    - by randombits
    I have a class that conforms to UISearchDisplayDelegate and contains a UISearchBar. This view is responsible for allowing the user to poll a store of about 17,000 objects that are currently managed by Core Data. Everytime the user types in a character, I created an instance of a SearchOperation (subclasses NSOperation) that queries Core Data to find results that might match the search. The code in the search controller looks something like: - (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope { // Update the filtered array based on the search text and scope in a secondary thread if ([searchText length] < 3) { [filteredList removeAllObjects]; // First clear the filtered array. [self setFilteredList:NULL]; [self.tableView reloadData]; return; } NSDictionary *searchdict = [NSDictionary dictionaryWithObjectsAndKeys:scope, @"scope", searchText, @"searchText", nil]; [aSearchQueue cancelAllOperations]; SearchOperation *searchOp = [[SearchOperation alloc] initWithDelegate:self dataDict:searchdict]; [aSearchQueue addOperation:searchOp]; } And my search is rather straight forward. SearchOperation is a subclass of NSOperation. I overwrote the main method with the following code: - (void)main { if ([self isCancelled]) { return; } NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; NSEntityDescription *entity = [NSEntityDescription entityForName:@"MyEntity" inManagedObjectContext:managedObjectContext]; NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; [fetchRequest setEntity:entity]; NSPredicate *predicate = NULL; predicate = [NSPredicate predicateWithFormat:@"(someattr contains[cd] %@)", searchText]; [fetchRequest setPredicate:predicate]; NSError *error = NULL; NSArray *fetchResults = [managedObjectContext executeFetchRequest:fetchRequest error:&error]; [fetchRequest release]; if (self.delegate != nil) [self.delegate didFinishSearching:fetchResults]; [pool drain]; } This code works, but it has several issues. It's slow. Even though I have the search happening in a separate thread other than the UI thread, querying 17,000 objects is clearly not optimal. If I'm not careful, crashes can happen. I set the max concurrent searches in my NSOperationQueue to 1 to avoid this. What else can I do to make this search faster? I think preloading all 17,000 objects into memory might be risky. There has to be a smarter way to conduct this search to give results back to the user faster.

    Read the article

  • Ruby on Rails: how to get error messages from a child resource displayed?

    - by randombits
    I'm having a difficult time understanding how to get Rails to show explicitly the error messages that a child resource is failing on when I render an XML template. Hypothetically, I have the following classes: class School < ActiveRecord::Base has_many :students validates_associated :students end class Student < ActiveRecord::Base belongs_to :school validates_format_of :email, :with => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i, :message => "You must supply a valid email" end Now, in the controller, let's say we want to build a trivial API to allow us to add a new School with a student in it (again, I said, it's a terrible example, but plays its role for the purpose of the question) class SchoolsController < ApplicationController def create @school = School.new @student = school.students.build @student.email = "bad@email" respond_to do |format| if @school.save # some code else format.xml { render :xml => @school.errors, :status => :unprocessable_entity } end end end end Now the validation is working just fine, things die because the email doesn't match the regex that's set in the validates_format_of method in the Student class. However the output I get is the following: <?xml version="1.0" encoding="UTF-8"?> <errors> <error>Students is invalid</error> </errors> I want the more meaningful error message that I set above with validates_format_of to show up. Meaning, I want it to say: <error>You must supply a valid email</error> What am I doing wrong for that not to show up?

    Read the article

1 2 3  | Next Page >