I figured out the solution of Alias $ in plugin code (I mean that if the user would like to use prototype and JQuery, they use noConflict and how does my plugin work?), I try to build my own JQuery plugin, hope it will come true soon
Custom Alias in plugin code
The trick is to define all plugin code inside a function and execute this function immediately. The construct looks like this:
(function() {
// put plugin code here
var xyz; // xyz is NOT a global variable, it is only visible inside this function
})(); // execute the function immediately!
The additional parentheses are necessary! You can't execute an anonymous function without them.
Ok, now to the fun part:
(function($) {
// plugin code here, use $ as much as you like
// This is my anwser
})(jQuery);
I found the answer at http://www.wisegeek.com/what-is-a-credit-card-gateway.htm, and hope it is useful for someone who read this article :D
A credit card gateway is one element of a suite of e-commerce
software packages that when incorporated into a website, allow for
online shoppers to pay for goods and services with VISA, MasterCard,
Discover, American Express or ATM debit card. To purchase items online, visitors add products to a virtual
"shopping cart" that holds item(s) while calculating a running tab of
charges. The shopping cart is provided by the host's e-commerce
bundle which can run anywhere from $50 - $100 per month, or more
depending on features. The customer clicks a "checkout" or "buy" button
when shopping is complete, and is transferred to a page generated by a
secure server. This server houses the credit card gateway. All data passed between the secure server and the customer's computer is encrypted
en route and only decrypts at the destination point. Before negotiation
starts, the secure server passes a certificate of authenticity to the
customer's browser to verify its legitimacy and identity. If there are
any problems with the certificate, the browser alerts the customer not
to continue with the transaction. Assuming this "handshake" goes well, the customer then supplies name, address and credit card
information and clicks "send" or "submit". The information is encrypted
by the browser then sent to the secure server and decrypted upon
arrival. The software protocols in the credit card gateway use the information provided to check for availability of funds and to make sure the credit card
is not expired, lost or stolen. This takes only seconds. When the
transaction is approved a receipt is generated for the customer, and
the funds are transferred to the vendor's bank account.
Rails (as of 2.1) provides different stores for the cached data created by action and fragment caches. Page caches are always stored on disk.
Rails 2.1 and above provide ActiveSupport::Cache::Store which can be used to cache strings. Some cache store implementations, like MemoryStore, are able to cache arbitrary Ruby objects, but don’t count on every cache store to be able to do that.
The default cache stores provided with Rails include:
1) ActiveSupport::Cache::MemoryStore: A cache store implementation which stores everything into memory in the same process. If you’re running multiple Ruby on Rails server processes (which is the case if you’re using mongrel_cluster or Phusion Passenger), then this means that your Rails server process instances won’t be able to share cache data with each other. If your application never performs manual cache item expiry (e.g. when you‘re using generational cache keys), then using MemoryStore is ok. Otherwise, consider carefully whether you should be using this cache store.
MemoryStoreis not only able to store strings, but also arbitrary Ruby objects. MemoryStoreis not thread-safe. Use SynchronizedMemoryStore instead if you
need thread-safety.
ActionController::Base.cache_store = :memory_store
2) ActiveSupport::Cache::FileStore: Cached data is stored on the disk. This is the default store and the default path for this store is: /tmp/cache. Works well for all types of environments and allows all processes running from the same application directory to access the cached content. If /tmp/cache does not exist, the default store becomes MemoryStore.
ActionController::Base.cache_store = :file_store, "/path/to/cache/directory"
3) ActiveSupport::Cache::DRbStore: Cached data is stored in a separate shared DRb process that all servers communicate with. This works for all environments and only keeps one cache around for all processes, but requires that you run and manage a separate DRb process.
ActionController::Base.cache_store = :drb_store, "druby://localhost:9192"
4) MemCached store: Works like DRbStore, but uses Danga’s MemCache instead. Rails uses the bundled memcached-client gem by default. This is currently the most popular cache store for production websites.
Special features:
- Clustering and load balancing. One can specify multiple memcached servers, and MemCacheStore will load balance between all available servers. If a server goes down, then MemCacheStore will ignore it until it goes back online.
- Time-based expiry support. See write and the :expires_in option.
- Per-request in memory cache for all communication with the MemCache server(s).
It also accepts a hash of additional options:
- :namespace- specifies a string that will automatically be prepended to keys when accessing the memcached store.
- :readonly- a boolean value that when set to true will make the store read-only, with an error raised on any attempt to write.
- :multithread – a boolean value that adds thread safety to read/write operations – it is unlikely you’ll need to use this option as the Rails threadsafe! method offers the same functionality.
The read and write methods of the MemCacheStore accept an options hash too. When reading you can specify :raw => true to prevent the object being marshaled (by default this is false which means the raw value in the cache is passed to Marshal.load before being returned to you.)
When writing to the cache it is also possible to specify :raw => true. This means that the value is not passed to Marshal.dump before being stored in the cache (by default this is false).
The write method also accepts an :unless_exist flag which determines whether the memcached add (when true) or set (when false) method is used to store the item in the cache and an :expires_in option that specifies the time-to-live for the cached item in seconds.
ActionController::Base.cache_store = :mem_cache_store, "localhost"
5) ActiveSupport::Cache::SynchronizedMemoryStore: Like ActiveSupport::Cache::MemoryStore but thread-safe.
ActionController::Base.cache_store = :synchronized_memory_store
6) ActiveSupport::Cache::CompressedMemCacheStore: Works just like the regular MemCacheStore but uses GZip to decompress/compress on read/write.
ActionController::Base.cache_store = :compressed_mem_cache_store, "localhost"
7) Custom store: You can define your own cache store (new in Rails 2.1)
ActionController::Base.cache_store = MyOwnStore.new("parameter")
config.cache_store can be used in place of
environment.rb.
In addition to all of this, Rails also adds the ActiveRecord::Base#cache_key method that generates a key using the class name, id and updated_at timestamp (if available).
An example:
Rails.cache.read("city") # => nil
Rails.cache.write("city", "Duckburgh")
Rails.cache.read("city") # => "Duckburgh"
ref http://guides.rubyonrails.org/caching_with_rails.html
I have been working with freelancers throughout my career and recently, thanks to services like oDesk, I find myself doing it more often. So you might think that I am happy with what I get, at least in general. Well, one of the reasons I continue to stay engaged is my high tolerance for pain – I am prepared to go through piles of hay to find that needle. And I have to tell you, looking for freelancers is very much like digging for gold – you literally have to go through tons of dirt to find it.
Interestingly enough many freelancers who have skills, knowledge and maybe even talent often torpedo themselves, aggressively sabotage their chances of getting customers right in the begging of the process. They make simple yet lethal mistakes that turn off clients before they got the chance to learn about freelancer’s ingenuity. Below are some of those mistakes:
- Not reading my post before you reply to it. Your three page long template proposal will get you in a recycle been faster than anything else. At least adjust your opening statement, show me that you read the post…
- Not using proper grammar and spelling. English is my second language and still work in progress; I still straggle with grammar myself, yet many responses I see push that envelope way too far. Grammatically poor introduction screams in my face “Communicating with this freelancer will be a real pain!” Spelling mistakes are even worse – how can I entrust my project to someone who doesn’t even make an effort to turn on a spellchecker?
- Talking with me like I am a teenager. Your slang (especially when combined with ESL marvels) comes across as complete lack of intelligence and class. By the way, spellchecker is not likely to recognize your “gonna”, “wanna”, “gimme”, take a hint.
- Being excessively polite. Your culture and language might require twenty minutes of praise and compliments before you get to business but I am an American, cut to the chase guy. More so, being overly polite and using somewhat unusual forms will telegraph a wrong image, your mentioning my “ultimate wisdom” only makes me think of a snake oil salesman.
- Not being punctual / prepared for your interview. I think of proposal / interview stage as a “honeymoon” in a relationship with a freelancer, it all goes downhill from there. Late for your Skype call? Having troubles finding your headset? Can’t introduce yourself? Chances are that’s the last time you’ll hear from me.
Don’t think I’m done here: I am only getting warmed up; it’s just my 500 word limit coming up. I guess will continue in my blog.
Nick Krym is a technology professional with over 25 years in the IT industry, and the author of the Pragmatic Outsourcing blog.
:(( After dig deeper to use Rails Engines & login_engine. I read this note
Ruby on Rails 2.3 Release Notes
Rails 2.3 delivers a variety of new and improved features, including pervasive Rack integration, refreshed support for Rails Engines, nested transactions for Active Record, dynamic and default scopes, unified rendering, more efficient routing, application templates, and quiet backtraces. This list covers the major upgrades, but doesn’t include every little bug fix and change. If you want to see everything, check out the list of commits in the main Rails repository on GitHub or review the CHANGELOG files for the individual Rails components.
=> rails engines plugin is out
This defines attr_accessors at a class level instead of instance level.
class Foo
cattr_accessor :greeting
end
Foo.greeting = "Hello"
This could be compared to, but is not the same as doing this:
class Bar
class << self
attr_accessor :greeting
end
end
Bar.greeting = "Hello"
The difference might not be apparent at first, but cattr_accessor will make the accessor inherited to the instances:
Foo.new.greeting #=> "Hello"
Bar.new.greeting # NoMethodError: undefined method `greeting' for #
This inheritance is also not copy-on-write in case you assumed that:
Foo.greeting #=> "Hello"
foo1, foo2 = Foo.new, Foo.new
foo1.greeting = "Hi!"
Foo.greeting #=> "Hi!"
foo2.greeting #=> "Hi!"
This makes it possible to share common state (queues, semaphores, etc.), configuration (max value, etc.) or temporary values through this.
Rails is a young framework, I thought it would be helpful to write up what I consider best practices when coding with it both for my new coworkers and the web at large. Here’s my current draft. Feel free to critique and comment. I’m very open to suggestions.
Testing
This is absolutely essential. Rails makes writing unit and functional tests incredibly easy and testing should be employed at all times. Positive and negative testing should be employed: the first to verify that the application does what it is supposed to when the proper variables are passed to the correct action and then second to verify that when incorrect variables are passed the prefered behavior occurs.
Unit Testing
As a general rule, unit testing should test any validation in models as well as any added methods in those models.
For example, if I have a User model which validates_presence_of first_name and last_name fields as well as a method fullname which combines the two, I might have test cases test_validates_names and test_fullname which would test that the model worked as it was intended to.
Functional Testing
Functional testing is used to test controllers. As a rule, there
should be atleast one testcase for each action and positive and
negative testing should be employed. This means that if I have an
action create in my PostsController then there should be test_create and test_bad_create
methods defined in my functional tests which do positive and negative
testing. This does not mean there should be only two tests for each
action. If there are exceptional cases beyond a simple good and bad,
proper testing should cover those cases.
Helpful Reading
Agile Web Development With Rails Chapter 12
Migrations
Migrations mean never having to say you’re sorry because you nuked the database. They allow for database agnostic schemas which means you can develop locally on SQLite and deploy on MySQL without a problem. They’re cleaner (and easier) than writing your own schemas custom and should be used whenever possible.
NEVER EVER EVER modify schema.rb. It is a reflection of the database. Migrations should be used to move this forward. If you don’t use migrations and instead modify schema.rb, things will break and people will be unhappy.
Note: You should always run svn update before generating a migration so you don’t have prefix collisions (two number 4s for example).
Helpful Reading
SQLite
SQLite is an SQL engine which runs in a single file rather than a server. It is (in general) as fast or faster than MySQL and is excellent for development and testing. In fact, it is possible to run a database completely out of memory which speeds up tests significantly. With the advent of migrations, it makes sense to use SQLite for testing as there is no extra work to deploy on MySQL.
DRY: Don’t Repeat Yourself
The main idea of DRY is that if code which is repeated is extracted to a helper or function, you only have one place to look for (and edit) your code if and when something goes wrong. If you find that similar code is used in several places, you may want to look into extracting that code to a helper function or partial.
Helpful Reading
Refactoring by Martin Fowler
Naming Conventions
Don’t use abbreviations, especially in database column names. It should be immediately obvious what the column is for (or atleast what the name means) when looking at the name. These are not the days of C, we don’t need to conserve space with our variable names. Additionally, Rails error handling automatically knows how to “humanize” column names, so when you use a well described name you get to work less on outputting errors.
If names are too long, try to think of another word or phrase that means the same thing, but is immediately obvious.
Source Control (Subversion)
Some sort of source control should be used at all times. This allows for easy roll back if something goes wrong as well as the ability to refer back to old code if needed. Rails has certain files which should not be included in a source control repository, so please refer to the wiki page when preparing the initial import.
Helpful Reading
Authentication Systems
Several authentication modules have been written for Rails, but some are better at some things and some are better than others.
acts_as_authenticated
This should be the prefered authentication plugin. It is easily installed via script/plugin,
is easily extendible and can handle all issues of the other
authentication modules. Additionally, the testing code is excellent
which makes it easy to modify.
login_generator
login_generator is the original login generator gem
written by Tobias Luetke. The downside is that there is a bug which
scrambles the password if you save an already existing user. It should
not be used for this reason. It is replaced and superceded by
acts_as_authenticated.
SaltedHashLoginGenerator
This was a first attempt at created a salted login generator which could reset passwords and do activation. It has since been extracted into login_engine. It is in general bloated and hard to modify. It should be avoided.
login_engine
login_engine is the extraction of SaltedHashLoginGenerator, and as such, has the disadvantages that SaltedHash has. Additionally, it uses the Rails Engines system which is designed for drop in use. In general, applications need customization. If you need more than simple modification of an authentication system, this should be avoided.
On Scaffolding
Scaffolding can be a time saver or a crutch. When using scaffolding, make sure to understand exactly what the code is doing and why. Once that happens you can generally write the code faster without using scaffolding as there are almost always changes to each section that scaffolding provides.
Suggested Reading (in General)
The Pragmatic Programmer by Dave Thomas and Andy Hunt
Refactoring by Martin Fowler
Agile Web Development with Rails by Dave Thomas and David Heinemeier Hannson
Programming Ruby by Dave Thomas, with Chad Fowler and Andy Hunt
Rubies and Gems: UUID
Often your application needs some form of UUID. For example for "Secret URLs" or Persistent Logins. I found the uuidtools to be very useful for this task. It allows you to create various forms of UUIDs (i.e. MD5, SHA1, Timestamp or Random).
Get the gem
-
sudo gem install uuidtools
And generate UUIDs
-
UUID.random_create.to_s
-
-
UUID.timestamp_create.to_s
and thats all there is about it.
Resources:
ref http://blog.simplificator.com/2007/10/24/rubies-and-gems-uuid/