More on RestController and some updates 2

Posted by Tim Connor Fri, 20 Apr 2007 18:58:00 GMT

I’ve fleshed out RestController, through some more usage. Combined with moving associated object creation into the model, it now really DRYs out my code, by being a little more flexible.

On any overridden action you can call super, passing in an option options hash. The current options are :template, which works for the editing template for errors on update and create and :find_options, for sorting the index view, for instance. As well, the instance variables (@page_title and @your_model_name) are set with ||=, so you can do custom init and then call super.

Well a picture is worth a thousand words, so, here are the public methods, using all of these techniques, from my most complicated controller on a project using it:

  def index(options = {})
    super ({:find_options => {:order => 'date DESC'}}.merge(options))
  end

  def public_index
    @page_title = 'Sun Valley Fishing Report'
    @body_class = 'archive'
    index :template => 'public_index'
  end

  def current
    @report = Report.current
    @page_title = 'Latest Sun Valley Fishing Report'
    public_show
  end

  def public_show
    @report ||= Report.find_by_date(params[:date])
    @page_title ||= 'Sun Valley Fishing Report'
    render :text => 'No report found', :layout => 'public' and return unless @report
    show :template => 'public_show'
  end

  def new
    @report = Report.new()
    Location.find(:all).each { |location| @report.conditions.build(:location => location) }
    super
  end

  def edit
    @report = Report.find(params[:id])
    Location.find(:all).each { |location|
      @report.conditions.build(:location => location) unless @report.locations.include?(location)
    }
    super
  end
Most of the other controllers ones are a couple of lines, maybe over-riding one action. For instance, here is my UserController, and even this might be simplified when I add in an error condition on edit and show (and/or an passed in error handling block):

class UsersController < REST::RestController
  def edit
    @user = User.find_by_id(params[:id])
    unless @user
      flash[:notice] = @@messages[:editing_invalid_id]
      redirect_to users_path and return
    end
    super
  end
end

UPDATE: Same day – I updated again, and now I can empty out that user controller, because the edit and show actions have basic checks for not found.

Dynamic-Scaffold-Resource is dead, long live RestController 4

Posted by Tim Connor Tue, 03 Apr 2007 18:39:00 GMT

I got tired of the complexities of my plug-in solution to DRYing up the shared code in all my Restful controllers, and scaffolding gets no love from core. But after a little while I got almost as tired of having the same 7 methods repeated throughout my code base. Thus a new simpler project is born: RestContoller.

Instead of scaffolding your views (which the core team is right about – those should diverge widely to fit the UI needs) or adding tests for you, it just gives you a main rest controller to inherit from that has the 7 basic actions (index, show, new, edit, create, update, and destroy). I was also able to simply further and drop the giant block eval, by looking over Jake Howerto’s CRUDController and borrowing a technique or two (such as the use of instance_variable_set). This should make the code easier to follow, customize, and also more performant.

You can just do a vanilla checkout from Google Code, and then inherit from that.

svn checkout http://restcontroller.googlecode.com/svn/trunk/ app/controllers/rest
class YourModelController < REST::RestController
but with this new approach it’s much more natural to customize per project. You can just go ahead and grab the file, save a local copy, check it into your own source control, and do with it as you will. For instance, if all of your resources have a public facing front, but the rest should be restricted, just add something like this (as well as the appropriate function in your application.rb)
before_filter :require_login, :except =>[:show, :index]

Backing up or transfering your data via YAML 4

Posted by Tim Connor Mon, 26 Mar 2007 21:27:00 GMT

Thanks to http://snippets.dzone.com/tag/fixtures. No warranties and no guarantees it’ll work on your full DB. I’m just using it for transferring around my starting data during dev.

Yes, I know part of this can be done with db:fixtures:load – but I don’t want to use ‘tests/fixtures’

lib/tasks/fixtures.rake

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

    desc "Load db/fixtures in fixtures_load_order" 
    task :restore => :environment do
      ActiveRecord::Base.establish_connection
      require 'active_record/fixtures'
      Fixtures.create_fixtures("db/fixtures", ActiveRecord::Base.configurations[:fixtures_load_order])
      puts "Loaded these fixtures: " + ActiveRecord::Base.configurations[:fixtures_load_order].collect { |f| f.to_s }.join(', ')
    end
  end
end
config/environments.rb

ActiveRecord::Base.configurations[:fixtures_load_order] = [
  :users, 
  :locations, 
  :reports, 
  :conditions
]

Alpha of subversion URL tab completion 3

Posted by Tim Connor Fri, 23 Mar 2007 23:32:00 GMT

Despite how much I really hate shell scripting I’ve actually got something semi-functional going on this whole svn tab completion idea. It only does anything when you tab on a full directory path (http://youserver/ or http://youserver/foo), but it will list the possibilities when you do, and autocomplete if there is only one.

I guess that just leaves getting partial completion working, ie http://yourserver/fo => http://yourserver/foo/, and then it’s done. I’m happy just to have it this far, though, so I won’t be cranking that out immediately. Down the road a bit maybe I’ll think about hostname completion too.

I cover the prerequisites in my quick intro to bash_completion of OS X. If you have that installed and the lastest svn bash_completion file, then you can just apply my patch.

bash_completion.patch.txt | bash_completion.patch

Index: bash_completion
===================================================================
--- bash_completion     (revision 24040)
+++ bash_completion     (working copy)
@@ -423,10 +423,19 @@
            return 0
        fi

-       # if not typing an option,
-       # then fallback on ordinary filename expansion
+       # if not typing an option
        if [[ $cur != -* || $stat = 'onlyarg' ]]  ; then
-           return 0
+          # if argument is an http directory
+           if [[ $cur == http://*/ ]] ; then
+             # strip leading http: due to completion issues with :
+            cur_path=${cur/http:/}
+             # query server and then prepend stripped path
+            ls_results=`svn ls $cur | sed s@^@$cur_path@g`
+            COMPREPLY=( $(compgen -W "$ls_results" -- "$cur_path") )
+            return 0
+          fi
+          # fallback on ordinary filename expansion
+          return 0
        fi

        # otherwise build possible options for the command
@@ -722,3 +731,4 @@
        return 0
 }
 complete -F _svnadmin -o default svnadmin
+

I forgot how much I really hate shell scripting

Posted by Tim Connor Fri, 23 Mar 2007 20:06:00 GMT

In 99.99% of the cases I’d just use a higher level scripting language, like ruby say, but when you are trying to extend existing shell scripted functionality…. I have learned a lot about programmable tab completion in bash, while trying to get subversion URL completion working, but I am still handicapped by my unfamiliarity with shell scripting, and my unwillingness to devote the next couple weeks to learning it.

I’m going to keep plugging at it here and there, but the url completion might take a while. If anyone out there is a decent bash scripter, I could use some pointers. ;)

The annoying part is the actual logic is pretty simple.

Dynamic Scaffold Resource moved to Google Code

Posted by Tim Connor Fri, 27 Oct 2006 04:21:33 GMT

Dynamic Scaffold Resource is now moved to Google Code. That has been the plan for a little while, but I had to get the repository reset, so I could svnsync the old repo up and keep the history.

Since this is a move to a project specific svn repository that has obviously been moved all around. And since the repository UIDs are different, you basically just need to do a clean checkout of trunk anyways:

http://dynamic-scaffold-resource.googlecode.com/svn/trunk/

Dynamic Scaffold Resource test helper now sucks less

Posted by Tim Connor Thu, 26 Oct 2006 07:00:00 GMT

I added a couple instance variables that can optionally be set so that the test helper can actually be used in something beyond the skeleton of the plugin’s own test environment. You can use it in an authenticated environment now, because you can set @scaffold_session_params and you can use it on resources that have validation in their models, because it will use @scaffold_dummy_object for the create and edit test, if you set it.

Didn’t change the core of the plugin itself, but the testing piece really was useless, so I had to add this just to use it on the project I made the plugin for in the first place.

Dynamic Scaffold Resource Rails plugin at final prerelease 2

Posted by Tim Connor Wed, 25 Oct 2006 23:48:00 GMT

I got everything I wanted done: testing, easy install, and documentation, so as of now Dynamic Scaffold Resource is ready to go. I’m holding off on making it officially 1.0 to see if there is any feedback from the people who expressed interest on the Rails core list.

While I know it could be fleshed out a lot more, my goal was to try as closely as possible meld the generated scaffold_resource and the dynamic scaffolding call, so as to make included it in Rails a better possibility. As such any feedback is still most, most welcome, but any new functionality would probably go in a post 1.0 branch. And there are a number of more fully featured scaffoldingesque plugins out there already, anyways.

Typo Plugin is live : permalink with ID is 1.0ish 4

Posted by Tim Connor Tue, 24 Oct 2006 18:51:00 GMT

So typo-permalink-with-id is fully operational. Your Rebel friends are doomed. For subversion or other project details go the project site at http://code.google.com/p/typo-permalink-with-id/.

To see it in operation try going to this article via the wrong permalink, like /articles/2006/10/24/25-tims-typo-plugin-is-so-cool.

Funny Rails shirts : test of the emergency broadcast system

Posted by Tim Connor Tue, 24 Oct 2006 18:46:00 GMT

This is a test of the new plugin.

Hey, look, funny Rails shirts

Older posts: 1 2 3