Page 29 of 30

Rails 2.0 scaffolding

The most valuable usage for scaffolding is when you use it in the administration part of the site. The administration is usually separated in separate module/folder.

The new rails scaffolding is not good because:

  • It is time taking to setup nested scaffold
  • I have tons of uselss source code in the scaffolding like respond_to ... that is usable very rare or never.
  • The HTML that is generated is ugly and not usable for CSS skin
  • Not using the nice ruby style iterations .each instead of for's
  • Code repetition, the “new” and the “edit” views has the same form elements
  • Not easy to find documentation

I find Akita article for scaffolding. It is is great that he has covered some real cases. It is a lot of reading and I must read/copy/paste every time I need to make a scaffold. Here is step by step on making scaffold for administration.

  • ruby script/generate scaffold admin::BadArticle NOT PLURAL!
    • user:references
    • description:text,string
    • fixed:boolean
    • timestamps are automaticaly added
  • Add in routes.rb
    • map.namespace :admin do |admin|
        admin.resources :bad_articles
      end
  • Model
    • Rename admin::BadArticles -> BadArticle,
    • move it to the model directory
    • rename the file
  • Fix the migration file:
    • remove the prefix from the migration class,
    • remove the prefix from table name
    • rename the file
  • URL references
    • admin_bad_articles_url
    • redirect_to([:admin, bad_article])
  • Controller
    • rename all Admin::BadArticles -> BadArticle except in the controller name
    • Probably you will want to make your scaffold inhired your base admin controller
    • def create
         ...
         format.html { redirect_to([:admin, @filtered_url]) }
         ...
      end
    • def update
          ...
              format.html { redirect_to([:admin, @filtered_url]) }
          ...
      end
    • class Admin::BadArticlesController < ApplicationController
      class Admin::BadArticlesController < Admin::AuthController
        layout 'admin'
       (in case that you don't have it in the base controller)
    • def index
        @admin_bad_articles = BadArticle.find(:all)
        respond_to do |format|
          format.html # index.html.erb
          format.xml  { render :xml => @admin_bad_articles }
        end
      end
  • Index.rhtml.erb
    • <td><%= link_to 'Edit', edit_admin_bad_article_path(bad_articles) %></td>
    • <%= link_to 'New bad_articles', new_admin_bad_articles_path %>
  • edit.rhtm
    • <%= link_to 'Show', @bad_article %> |
      <%= link_to 'Back',bad_articles_path %><%= link_to 'Show', [:admin, @bad_article_url] %> |
      <%= link_to 'Back', admin_bad_articles_path %>
  • show.html.erb
    • <%= link_to 'Edit', edit_filtered_url_path(@filtered_url) %> |
      <%= link_to 'Back', filtered_urls_path %>
  • new.rhtml
    • <% form_for(@bad_article) do |f| %><% form_for([:admin, @bad_article]) do |f| %>
    • <%= link_to 'Back', bad_articles_path %><%= link_to 'Back', admin_bad_articles_path %>

Traps:

The order of the routes in routes.rb does matter! In order to make the REST work you must have this block at the bottom of your routes.rb like this:

map.namespace :admin do |admin|
  admin.resources :bad_articles
end
# Install the default route as the lowest priority.
map.connect ':controller/:action/:id.:format'
map.connect ':controller/:action/:id'


Remove simply_helpful plugin if you get the error:

undefined method `new_record?' for #Array:0x532a3e8

Debuging tools:

rake routes

Tips:

How to add custom actions to the REST

map.namespace :admin do |admin|
  admin..esources :bad_articles, :member => {:toggle => :get}
  admin.resources :orders, :member => { :resend => :post }
  admin.resources :users,  :collection => { :filter => :any }
end

Then in the controller:

def toggle
  @bad_article = BadArticle.find(params[:id])
  @bad_article.fixed = ! @bad_article.fixed
  @bad_article.save
  redirect_to  admin_bad_articles_url
end

And in the view:

<%= toggle_admin_bad_article_url(filtered_url) %>

More reading here

Resources:

Game

Once in the dark DOS ages I have one game with which you can make wonderfull animations. In the “Windows” era I miss this game a lot….until I found this nice replacement.

http://phun.cs.umu.se/wiki/Download

Firefox extensions

Here is the list of the firefox plugins that I use.

Online books storages

Using google

  • intitle:”index of” “head first” -free -examp -preview

Javascripts

Good prototype controls

http://livepipe.net/#hoverbox

Directly print pdf files from a browser

function Printobject(){
document.all.PDF.print();
setTimeout(“self.close();”,4000); }

Rails code-snipplets

auto_scope

source: http://blog.teksol.info/archives/2007/3

class Contact < ActiveRecord::Base
auto_scope \
:old => {:find => {:conditions => [born_on < ?, 30.years.ago]}},
:young => {:find => {:conditions => [born_on > ?, 1.year.ago]}}
end

class Testimonial < ActiveRecord::Base
auto_scope \
:approved => {
:find => {:conditions => [approved_at < ?, proc {Time.now}]},
:create => {:approved_at => proc {Time.now}}},
:unapproved => {
:find => {:conditions => approved_at IS NULL},
:create => {:approved_at => nil}}
end

Rails internals!?

http://localhost:3000/rails/info/properties

Threads

Programs for Linux

Ubunto repositories

Home

winetricks

wget www.kegel.com/wine/winetricks
example: ./winetricks winver=winxp
example: ./winetricks vcrun2005

http://www.virtualbox.org/

Disk managment
KDirStat and Baobab

Security

http://pakiti.sourceforge.net/ – monitor and install patches on multiple servers, supports ubunto, and rh

games

LiveCD

Clipart – links

Image repositories

http://photl.com/en/93728.html – abs free

http://www.stockxpert.com/browse.phtml?f=view&id=211606
http://www.shutterstock.com/
http://www.stumbleupon.com/

How to choose colors for the websites:

http://kuler.adobe.com/

http://www.colorcombos.com/

Html templates/css

http://www.tristarwebdesign.co.uk/templates.php

http://www.cssdrive.com/

http://drupal.org/project/Themes

http://boygj.com/TemplateMonster

favico generators + icons

http://www.html-kit.com/favicon/
http://www.smashingmagazine.com/2007/06/20/ajax-javascript-solutions-for-professional-coding/

Icons

http://www.iconarchive.com/category/application/buuf-icons-by-mattahan.html

Javascript image galleries

  • Catalog of galleries: http://tutorialblog.org/12-javascript-image-galleries/
  • http://www.zenphoto.org/2008/08/installation-and-upgrading/
  • http://www.artviper.de/ImageMenu/

Масапан

Незнам защо но успях да открия в интернет само тази рецепта за тези вкусни бонбони и се изуших да я запазя за ентусястите, в момента бадемите са в хладилника и побеляват активно.

200 гр. сурови бадеми
90 гр. захар
130 гр. вода
1 ч. л. лимонов сок

Бадемите се накисват във вряла вода, която да ги покрие два пръста. Престояват така около 20-30 минути и се обелват, като се натискат леко в края на ядката.
Слагат се върху домакинска хартия и така престояват една нощ в хладилника, за да се изтегли водата от тях и за да побелеят.
На другият ден бадемите се смилат фино в машинка за кафе или в кухненски комбайн, до консистенция почти на брашно. За по-добър резултат се слагат по малко бадеми, защото при по-големи количества долния пласт става на паста, а горният е едро смлян. Прави се захарен сироп от захарта и водата по следния начин-слагат се двете съставки в дълбок съд и се оставя да заври сместа. После се намаля котлона на средна степен и се оставя сиропа да ври докато не стане със следната консистенция-като се капне капка от него в чаша със студена вода, то капката трябва да падне цяла на дъното,
Когато този момент (Punto di masapan) е достигнат, смлените бадеми се прибавят и вече на съвсем слаб котлон се превъртат заедно със сиропа, докато не стане хомогенна тестообразна смес. Тенджерата се отсранява от котлона, хубаво се смесва с лимовият сок и се приготвят бонбони с помощта на метална формичка и найлоново опаковъчно домакинско фолио-фолиото се слага във формичката, отгоре се натъпква плътно сместта и се обръщат така получените бонбони върху пекарска домакинска хартия.
След като се стегнат се нареждат в празна картонена кутия от бонбони и преседяват още една нощ в хладилника.
На другият ден можете да опитате този невероятно вкусен еврейски сладкиш, който се приготвя за сватби, раждане на деца, Брит мила или Бар или Бат мицва.
Той има особен статут в еврейската култура, защото приготвянето му отнема много време и е относително скъп за направа.

Източник
masapan

Software and Tutorial Links

IPTables
Linux firewall with packet string-matching support
http://www.securityfocus.com/infocus/1531
Firewall scripts
http://linuxfirewall.start.bg/
http://www.puschitz.com/FirewallAndRouters.shtml
Debian Kernel how-to
http://myfreesoft.net/phpBB2/viewtopic.php?t=52 * in Bulgarian *
Source: http://www.howtoforge.com/forums/showthread.php?t=21
http://www.howtoforge.com/kernel_compilation_debian
Active Ports (Windows)
http://www.microsoft.com/technet/sysinternals/Networking/TcpView.mspx
Security and Audits Checks & updates
http://sourceforge.net/projects/advchk
RedHat – http://www.redhat.com/spacewalk/

© 2025 Gudasoft

Theme by Anders NorénUp ↑