Friday, January 29, 2010
Awesome Taxonomy module for categorise content in drupal
A small Tip
["foo", "bar"].each do |method|
MyClass.send(method)
end
The above code is same as calling MyClass.foo and MyClass.bar.
Make your rails application DRY with constants
One of the ways I utitilise constants is to standardise the date formatting I use across an app.
For example, in environment.rb I will create a module to contain my date format constants:
module Dates
DATE_FORMAT = "%d% %b %Y"
DATE_TIME_FORMAT = "#{DATE_FORMAT} %H:%M"
end
The module just groups them nicely together. To use the constants I will write the following:
@object.created_at.strftime(Dates::DATE_FORMAT)
@object.created_at.strftime(Dates::DATE_TIME_FORMAT)
Remember you will need to restart your server after making any changes to environment.rb
Helpers usage in ROR
Using helpers is simple, each controller has it's own helper file or you can write helpers in the application helper file if it will be used across the entire application. For example a pagination helper might go in there.
def my_helper(opts={}) #args defined as hash
"output something" if opts[:method_passed_in] == "foo"
end
You can then use it in your view with:
<%= my_helper('foo') %>
Ruby on Rails User multiple layouts in single controller
layout :choose_layout
private
def choose_layout
if [ 'signup', 'login' ].include? action_name
'login'
else
'admin'
end
end
Alternate row colors for table rows in Ruby on Rails
<%- for item in @items do -%>
tr class="<%= cycle("even", "odd") %>"
... use item ...
/tr
<%- end -%>
Then in your stylesheet add below
tr.even td{
background-color:#CCC;
}
tr.odd td{
background-color:#EEE;
}
Thursday, January 28, 2010
Solution to Undefined method `cache_template_extensions=' in Ruby on Rails
the below error
Undefined method 'cache_template_extensions='
To fix this problem check your environment.rb and environemts/development.rb, production.rb, test.rb files and comment/remove the below line of code.
config.action_view.cache_template_extensions = false
Restart the server and see output.
Solution to uninitialized constant FileColumn::ClassMethods::Inflector in Ruby on Rails
my_options = FileColumn::init_options(options,
ActiveSupport::Inflector.underscore(self.name).to_s,
attr.to_s)
Also at line number 79 find and change as below
url << size="4">Restart the server and see the output.
Wednesday, January 20, 2010
Solution to Google checkout payment gateway oops error
by login with your merchant details then Goto
Tools -> Integrated console
There you can see the log of what problems occured while users try to pay you.
Linux chage folder permision to a group
Hi, In linux root have the full permission over entire os and other users will have some previliages only. So when you loggin to the system and want to have write permission to one folder all you have to do, first see the permission of that folder, it contains three blocks,
OWNER - root
GROUP - root
OTHERS --
Here this means all all writes are permitted to root only. If you want to have write permission to this folder, First change the group permission to your group, then provide the write permission to the group. For this follow the below commands
First login as superuser that i.e root for this run command 'su' in the terminal
sudo su
enter root password:
chgrp -R venkat /var/www
#the above command will change the group
chmod -R g+w /var/www
#the above command will provide the write permission to the group
Now the user who logged in as venkat can have the read write permission to the folder var/www
r = read permission
w = write permission
x = execute permission
- = no permission
Ref: http://www.tuxfiles.org/linuxhelp/filepermissions.html
http://www.comptechdoc.org/os/linux/usersguide/linux_ugfilesp.html
Tuesday, January 19, 2010
Remove N/A option for radio buttons and select boxes in Drupal using CCK
if (!$field['required']) {
if ((in_array($field['widget']['type'], array('optionwidgets_buttons', 'nodereference_buttons', 'userreference_buttons')) && !$field['multiple'])
|| (in_array($field['widget']['type'], array('optionwidgets_select', 'nodereference_select', 'userreference_select')))) {
$options = array('' => theme('optionwidgets_none', $field)) + $options;
}
}
Now the N/A option is not displayed for radio buttons and select boxes.
Allow users to select Roles while Registration in Drupal
http://drupal.org/project/user_selectable_roles
After install it in your application, you should goto administer->user mangement-> user_select_roles
There you can set which roles are displayed in the registration form and other options to select multiple roles selection or single etc.
Restrict accessing your site for some users based on their IP Address
In .htaccess add below lines
Order allow, deny
Deny from 192.168.0.10
Deny from 1.2.3.4 5.6.7.8 127.0.0.1
Allow from all
It is allowed accessing for all except fom IPs 92.168.0.10,
127.0.0.1,127.0.0.2,127.0.0.3
--------------------------------------------------------------
OR if you want to access your site from your IP only add below lines in .htaccess file
Order deny, allow
Deny from all
Allow from 192.178.0.10
This will be usefull for your site administrators.
If you set this for site admin, then the administrator can access admin area from the mentioned IP only.
Run PHP Code in HTML files
For web servers using PHP as apache module:
AddType application/x-httpd-php .html .htm
For web servers running PHP as CGI:
If your requirement is only for one page then use below code
AddHandler application/x-httpd-php .html .htm
AddType application/x-httpd-php .html
Thursday, January 7, 2010
Ruby on Rails Fat model and skinny controller
#app/model/gallery.rb
class Gallery < ActiveRecord::Base
def self.get_related(galname)
related = find(:all, :conditions => ['name like ?', '%'+galname+'%'])
end
end
#app/controllers/galleries_controller.rb
class GalleriesController < ApplicationController
def show
@gallery = Gallery.find(params[:id])
@related = Gallery.get_related(@gallery.name)
end
end
#app/views/galleris/show.rhtml
Related Galleries
<% @related.each do |relate|%>
<% if (relate.id!=@gallery.id)%>
<%= link_to( relate.name , { :action=>'show', :id=>relate.id}) %>
<% end %>
<% end %>
Ruby on Rails shareble content or menus processing
Ex: app/views/shared/_global_links.rhtml
<% if logged_in? %>
<%= current_user.login %> |
<%= link_to "Dashboard", root_url %> |
<%= link_to "My Account", profile_url(current_user) %> |
<% if admin? -%><%= link_to "Administration", admin_root_url %> | <% end -%>
<%= link_to "Log out", logout_url, :method => :delete %>
<% else %>
<%= link_to "Sign up", signup_url %> |
<%= link_to "Log in", login_url %>
<% end %>
#app/views/layouts/application.rhtml
-------------------------------------------------------
-------------------------------------------------------
<%= render :partial => 'shared/global_links' %>
-------------------------------------------------------
-------------------------------------------------------
Ruby on Rails Dynamic content blocks using contentfor and yield helpers
----------------------------------------------------------
<%= yield_or_default(yield(:sidebar)) %>
-----------------------------------------------------------
In app/views/users/index.rhtml you should set the content for rightcolumn for the users page like below
-----------------------------------------------------------
<% content_for :sidebar do -%>
Sidebar
- Add your photos
- View your galleries
- <%= link_to "Log in", login_url %> Login
<% if logged_in? %>
<% else %>
<% end %>
<% end -%>
-----------------------------------------------------------
In In app/views/movies/index.rhtml you should set the content for rightcolumn for this movies page like below
-----------------------------------------------------------
<% content_for :sidebar do -%>
some movies related information you can place here
<% end -%>
-----------------------------------------------------------
Rails use :select for better performance
Example use below
@movies = Movie.find(:all, :select => 'title, description')
instead of
@movies = Movie.find(:all)
It will get only the title and description and store into instance variable (hash) @movies.
Here you application load time will definetly decreased.
About Drupal Framework
Why Drupal? What's a Framework?
A brief history of web applications
I think about web technologies as a series of layers. At the bottom, you've got the computer hardware that hosts your site. At the top, you've got what you see in your web browser--a bunch of text, pictures, videos, and ways of interacting with that content. In the middle are all the bits and pieces that get put together to create what you see in your browser.
In the early days of the web, there were pretty much 3 layers between the hardware and your web pages: the operating system on the server, a program called a web server that sent the pages to your browser, and a collection of HTML files and images that contained the content.
Early on, web servers started handing off particular requests to other programs, which could generate HTML on the fly and do other actions. The earliest mechanism for this was called CGI (Common Gateway Interface), and it allowed programmers to process data sent by forms, store and retrieve data from databases. At this point we quickly got to the point where we had stacks of software that work together to make more dynamic web sites. One of the most popular stacks is called LAMP, for the Linux operating system, Apache Web server, MySQL database, and PHP (or Perl or Python) language. A programmer can write programs in PHP to interact with a database and give you pages that are not just static files stored on the server, but generated on the fly. These pieces were all in place and in fairly widespread use by 2000 or so. Programs written in PHP on the web have come to be called "Web Applications."
What's a web application?
Quite simply, a web application is just a program that runs on a web server that you access through a web browser. We've built web applications to manage client data for a legal association, manage photos, manage who on a team is going to come to each game, track time spent on tasks and projects, sell products through the web in both a wholesale/manufacturing environment and for retail, and many others. We've deployed web applications for managing the financial records for a business, manage contacts with clients, report on electricitly usage in a house, all kinds of things. Database applications can solve all kinds of business needs, in all kinds of ways. Web applications are simply database applications you can access with an Internet connection and your web browser.
Most web applications are built to solve one kind of problem, and solve it well. Often if you start with an application made for one purpose, it's very difficult to repurpose it for another. Content management systems are not usually interchangeable with contact management systems. If you deploy a system designed for making it easy to publish blog posts, you're not likely going to find it useful for selling products--you'll need a different system. A system built to manage games and sports teams is not likely going to work well for tracking recipes.
What's a Content Management System?
You'll hear them called a "CMS" for short. Content management systems are web applications that are built to manage content on a web site. Their job is to make it so that you can easily edit or add new content to your web site without needing special tools. There are hundreds of different CMSs out there, each with different strengths and weaknesses. We've worked extensively with Joomla, Word Press, MediaWiki, and several others, but Drupal is our core CMS these days--because it's flexible enough to do more than just manage content.
What's a Framework?
Let's peel back a layer and look at what's under the hood. A Content Management System is a particular kind of web application. A framework is a set of tools and a pre-defined architecture for building a web application. So you could quite easily build a content management system on top of a framework.
Have you heard of Ruby on Rails? Rails is a framework, written in the Ruby programming language. Other popular frameworks include Django, CakePHP, Symfony, and dozens of others.
Most frameworks provide a built-in architecture to rapidly develop a full-blown web application. They often tend to use a "Model-View-Controller" organization -- a common way of dividing up programming tasks into units that can be managed more effectively. The "Model" represents the various objects your application manipulates -- pages, customers, projects, addresses, whatever. The "View" is usually the layer that graphic designers work with, to provide a look-and-feel for the application. The "Controller" ties all the bits together, determines who can access what and how it all works. In grammar terms, elements of the model are nouns, the view is mostly adjectives, and controllers are the verbs.
Powerful stuff. Frameworks are great. Except there's one big problem with using a framework, when there's already a good application for you to use: you still have to build an application!
If you're building a web site to manage content, and you're starting with a framework like Rails, it's like building a car from a kit instead of buying one off the lot: you have to do a lot more work before you can start driving.
If you need an application to do something you can't do in an existing application, a framework may well be the way to go. But before doing that, first see if there's an application that does the job for you already. If there is, your first step becomes putting your data into the application, not building the application.
Drupal as a Framework
Drupal is a fine content management system all on its own. But its true strength is that it's flexible enough to do many things beyond just managing content, while remaining modular enough to keep it simple.
Drupal provides quite a lot of base functionality that developers can leverage to rapidly develop all kinds of applications. The key things include:
- A complete user authentication system, with plug-ins for OpenID, LDAP, and many other systems
- A robust role-based authorization model
- Any number of "Content Types" may be defined, using default handlers overridden where necessary, for storing content objects and relationships
- A flexible taxonomy system that can be used to categorize and tag content
- The "Forms API" to make it simple to create, validate, and process forms and uploaded files
- Multiple theme engines with a clear override system for theming individual elements and pages
- A sophisticated URL-parsing system to hook functionality to particular paths
- An extensive hook system allowing you to completely change the behavior of the application at a fundamental level
- Built-in caching, Javascript and CSS optimization, and cache-busting features for a nice mix of performance and development flexibility, and
- Thousands of additional modules to make all sorts of changes to the system, including workflow rules, e-commerce, access control, automatic image processing and much more.
That's just a taste of what you can do with Drupal. There's a very definite learning curve before you'll know how to do all of this--which is why it's worth hiring a company like us to get you started. But there's a similar learning curve involved in using any framework effectively, too. The difference is, with Drupal you can start with a working site and easily add features as you go.
Why wouldn't you use Drupal?
There are a lot more specific applications that do particular things, and do them well. Want to manage your customer relationships? SugarCRM is a good place to start. Manage your business finances? LedgerSMB. Have a standalone desktop application you can use offline? Not Drupal. We've recently used LimeSurvey for a couple projects that used very sophisticated question formats, and it still met the need better than the Quiz module in Drupal.
If your needs are limited, and your site is meant to have a single function, you might be able to start more quickly and with less cost with a more specific solution. But if you need to build something custom, we're not seeing very many applications that can't be done well in Drupal. There are people in the Drupal community building clones of popular sites like Facebook, Twitter, Flickr, Basecamp, YouTube, and others, just to see how well Drupal can do the job. All can be done pretty quickly by a knowledgeble Drupal person, without much custom code.
The other place we've been working without Drupal is on web applications that have a huge amount of Javascript. Drupal is fine as a back end for a lot of different systems, though in some cases a simple framework storing resources managed from the browser may be a better way of supporting heavy Javascript-based applications. We're doing this for some charting/dashboard systems and a management application that puts a lot of functionality into a single browser window.
How do you choose?
Pick the best tool for the job, accounting for your priorities.
If there's already an application that does exactly what you need, use it.
If you need a custom web application, and need to manage users, objects, authentication/authorization, workflow, and other common features, consider using Drupal as a framework.