How to call a method in Java

A method is a collection of statements that are grouped together to perform a specific task. Methods are a key part of object-oriented programming and provide a way to modularize code. In Java, methods are defined within classes and are accessed using the class name followed by the method name.

How to call a method in Java

To call a method in Java, you need to know the following:

  1. The name of the class that contains the method.
  2. The name of the method.
  3. The parameters of the method, if any.
  4. The return type of the method.
  5. The order of the parameters.

Let’s look at an example. The following code snippet defines a class called Employee and contains a method called calculatePayment().

class Employee {

public static void calculatePayment(int hours, int rate) {

double payment = hours * rate;

System.out.println(“Payment for ” + hours + ” hours at ” + rate + ” per hour is ” + payment);

}

}

Parameters of a method

A method can have zero or more parameters. The parameters of a method are the values that are passed to the method when it is called. In the example code snippet, the calculatePayment() method takes two parameters, hours and rate.

The parameters of a method are always specified in the order in which they are to be passed. In the example code snippet, the first parameter is hours and the second parameter is rate.

Return type of a method

The return type of a method is the type of the value that is returned by the method. In the example code snippet, the return type of the calculatePayment() method is double. This means that the method returns a value of type double.

When a method returns a value, the value is assigned to a variable that is defined in the calling code. In the example code snippet, the payment variable is defined in the calling code and it is of type double. This means that the value returned by the calculatePayment() method is assigned to the payment variable.

Overloading a method

A method can be overloaded, which means that the method has multiple signatures. A signature is a combination of the name of the method, the number of parameters, and the type of the parameters. In Java, the method name and the number of parameters must be the same, but the type of the parameters can be different.

In the example code snippet, the calculatePayment() method is overloaded. The first signature takes two parameters, hours and rate, and the second signature takes one parameter, hours.

Method invocation 

The process of invoking a method is the same for both static and non-static methods. The only difference is that for static methods, the class name is prefixed to the method name, whereas for non-static methods, the object reference is prefixed to the method name.

When a method is invoked, the following steps are executed:

  1. The Java Virtual Machine searches for the method in the class that contains the source code of the program.
  2. Searches for the method in the superclasses of that class.
  3. Searches for the method in the superclasses of the superclasses of that class.
  4. Searches for the method in the Java Class Library.

If the method is not found, an error is thrown.

Conclusion 

Methods are the basic units of functionality in Java. They are declared in a class and are invoked on objects of that class or its subclasses. A method is overloaded when it has the same name but different argument types. When a method is invoked, the Java Virtual Machine searches for the method in the class that contains the source code of the program, and then in the Java Class Library. If the method is not found, an error is thrown.

How does a cryptocurrency gain value

There’s a lot of confusion around how cryptocurrencies gain value. Some people seem to think that cryptocurrencies are like stocks, and that the price is simply a reflection of how much people are willing to pay for them. You can get the most up-to-date information about cryptocurrencies at finpr.agency

Others think that cryptocurrencies are like commodities, and that their value is based on how much utility they provide.

The truth is, cryptocurrencies gain value in a much more complex way than either stocks or commodities. Their value is based on a combination of factors, including how much people are willing to pay for them, how much utility they provide, and how rare they are.

To understand how cryptocurrencies gain value, we first need to understand what they are. Cryptocurrencies are digital or virtual tokens that use cryptography to secure their transactions and to control the creation of new units. Bitcoin, the first and most well-known cryptocurrency, was created in 2009.

Cryptocurrencies are often compared to stocks, but they are actually quite different. Stocks are shares in a company, and their price is based on how much people are willing to pay for them. Cryptocurrencies, on the other hand, are not shares in anything. Their price is based on a variety of factors, including how much people are willing to pay for them, how much utility they provide, and how rare they are.

Cryptocurrencies can be used to purchase goods and services, just like regular currencies. However, they also have other uses. For example, Bitcoin can be used to pay for goods and services on the internet, and can also be traded for other cryptocurrencies or for regular currencies.

Cryptocurrencies are also quite rare. There are only a limited number of them, and they are not produced by governments or central banks. This makes them more like commodities than currencies.

The combination of rarity, utility, and demand drives the price of cryptocurrencies. The more people want them, the higher the price will go. And the more people use them to purchase goods and services, the more valuable they become.

What are the risks of investing in cryptocurrencies?

Are you thinking about investing in cryptocurrencies? Well, you should be very careful, because there are a lot of risks involved!

First of all, the value of cryptocurrencies can fluctuate a lot. For example, in January 2018 the value of Bitcoin dropped by more than 50% in just a few months. So if you invest in cryptocurrencies, you could lose a lot of money if the value drops suddenly.

Second of all, the cryptocurrency market is very volatile. This means that the prices of different cryptocurrencies can change very quickly, and it’s not always easy to predict what will happen. So if you invest in cryptocurrencies, you could lose a lot of money if the price changes suddenly.

Finally, the cryptocurrency market is very risky. This means that there is a lot of chance that you could lose your money if you invest in cryptocurrencies. So if you invest in cryptocurrencies, you could lose a lot of money if the market crashes.

So, are you still thinking about investing in cryptocurrencies? If not, you should probably reconsider!

What are the benefits of investing in cryptocurrencies?

1. Increased Privacy and Security

One of the key benefits of cryptocurrencies is that they offer increased privacy and security. Unlike traditional currencies, cryptocurrencies are digital and decentralized, meaning they are not subject to government or financial institution control. This makes them far more secure and less vulnerable to hacking and theft.

2. Increased Freedom and Control

With cryptocurrencies, you have complete control over your money. You are not at the mercy of financial institutions or governments when it comes to using, spending, or investing your money. This gives you greater freedom and control over your finances.

3. Faster, More Convenient Transactions

Cryptocurrencies are also much faster and more convenient to use than traditional currencies. Transactions are completed nearly instantaneously, and there are no bank fees or other transaction costs involved.

4. Increased Investment Opportunities

Cryptocurrencies are also a great investment opportunity. Their value has been steadily increasing over the years, and they are likely to continue to do so. This makes them a wise investment choice for those looking to secure their financial future.

5. Increased Access to Financial Services

Cryptocurrencies also offer increased access to financial services for those who do not have traditional access to them. This can be especially beneficial in developing countries where banking and financial institutions are not well-developed.

Overall, there are many benefits to investing in cryptocurrencies. They offer increased privacy and security, freedom and control over your finances, and increased investment opportunities. They are also a great way to access financial services in developing countries. If you are thinking of investing in cryptocurrencies, be sure to do your research first to ensure you are making an informed decision.

What to choose: relocate or work from home?

When considering working from home or relocating for your job, it’s important to weigh the pros and cons of each option.

Working from home is less risky; you can keep your day job while working on other projects in the evening or on weekends. It also provides you with more free time to be spent with family and friends.

On the other hand, working online can be done without moving all your belongings to another city. You can choose a city that offers what you’re looking for in terms of work opportunities and lifestyle, and then commute back and forth as needed.

Relocating can bring a lot of new opportunities – meeting new people, trying new things, exploring different cultures. If you’re willing to take the risk, it’s worth the investment.

Relocating your job most definitely will make you meet new friends and experience new adventures. It also can be a great way to learn more about different cultures and lifestyles – working overseas is one of the most rewarding experiences someone could have in their career path. There are many benefits that come along with working from home as well!

How to earn money working from home?

The internet has made working from home a more viable option than ever before. There are now a number of ways to make an income without having to leave your house. One such way is through financial trading.

With that knowledge in hand, you can then start making informed decisions about your trades and hopefully see some success. Remember, always use caution when trading online; it’s easy to lose money on scams if you’re not careful!

If you’re looking for a career in trading – consider CFDs trading. And if you’re already working from home and are looking for ways to increase your income, be sure to check out our tips on how to make more money from home. Good luck!

  1. Trading can be profitable, but it also requires time and learning to do correctly
  2. Remember, always use caution when trading online; it’s easy to lose money if you’re not careful!
  3. For more information on how to get started with financial trading, check out online tutorial series or use demo versions on online trading platforms.

Why CFD Trading?

CFD trading is becoming more and more popular every day. This is because it offers a lot of advantages over traditional trading methods. Let’s take a look at some of the main benefits of CFD trading:

First, CFDs offer high leverage. This means that you can control a larger position than you would be able to with your own money. This gives you the opportunity to make bigger profits, but it also adds an additional risk. If the trade goes against you, you could lose more money than you have invested.

Second, CFDs are available 24 hours a day, five days a week. You can trade whenever market conditions are right for you.

Third, CFDs allow you to trade on margin. This means that you can use CFDs to take advantage of both rising and falling markets.

Fourth, CFDs are very liquid instruments with low transaction costs. There is no need to worry about finding enough buyers or sellers when trading CFDs as there would be with stocks or futures contracts because CFD prices reflect the underlying market price for these assets directly.

Finally, CFDs allow you to trade a wide range of assets. You can trade CFDs on stocks, indices, commodities, and currencies. This gives you the flexibility to trade the markets that interest you most.

So why should you consider trading CFDs? There are a number of reasons: high leverage, 24-hour availability, margin trading, liquidity, and asset diversity. CFD trading offers many advantages over traditional methods and is becoming more popular every day. Give it a try today!

Conclusion

Job relocation can be a good solution, but it comes with many drawbacks! But working remotely doesn’t have to mean putting up with living abroad on top of working long hours. If you want to start working from home you might look into financial trading.

Trading can be profitable, but it also requires time and learning to do correctly. Before you dive in, it’s important to educate yourself on the basics of trading and the risks involved.

So why should you consider trading CFDs? There are a number of reasons: high leverage, 24-hour availability, margin trading, liquidity, and asset diversity. CFD trading offers many advantages over traditional methods and is becoming more popular every day. Give it a try today!

Some Important Questions About Relocate For Job

Reasonable Time To Relocate For A Job

The time it takes to relocate for a job is also addressed in the law. If an employee has worked over 12 months for their employer, they can’t be fired without reasonable warning or opportunity to correct (except in cases where the employer’s business suddenly shuts down because of the financial crisis). Taking into consideration all relevant circumstances, what is a reasonable time will vary from case to case. However, employers should keep these general factors in mind:

  • The distance and travel time to work for both parties;
  • Expenses involved (e.g., moving truck rental)
  • How much notice is required by either party?
  • What type of jobs are involved? Low-paid jobs typically require less relocation period than higher-paid jobs, which involves more complex relocation arrangements.
  • How many workers (i.e., one or more) will be affected and how critical is the labor shortage?
  • The responsibility of the employer is to find a new position for its employees; while on the other hand, employees bear the responsibility to look for new jobs where they are relocated.

Reasons To Relocate For A Job

There are many reasons to relocate for a job. Here are some of the most common reasons:

  • A new job in another place, which is either highly paid or highly qualified;
  • Better working conditions;
  • The chance of promotion;
  • Taking care of family members (e.g., parents with health problems) or being closer to family members (e.g., children studying at university).

It is important to say that relocation benefits vary from one person to another; thus, the main factors of such benefits are:

  • A new job;
  • The number of years that an employee has worked for the company;
  • The wage difference between the old job and the new job.

“For some companies, it makes sense to have employees relocate for a certain period, but retain them on staff after their term is up.”

It’s not just about economics. If you move away from your home overnight, you will feel surprised by how much things change in so little time. You can imagine what you could feel if it were longer than a year.

Reasons To Relocate For A Job

Should I Relocate For A Job?

One of my best friends moved to Washington after she got married. It’s so expensive but her salary was increased by 30%. She likes it now, though. If you’re considering relocating for a job, think about the following:

  • Do I like the location?
  • How much will I be making? Is the money worth the stress and time it takes to move (and find an apartment)?
  • What do people in my profession make in that area? Are they happy with their careers? Will I be satisfied with the work culture or career path?
  • Have I researched housing prices and school districts in that area?

Relocation benefits are available through many companies today. Usually, relocation benefits include moving expenses, temporary housing for up to three months, reimbursement for travel to the area, and help finding an apartment. However, these benefits are usually given only once every five years.

If you’re not ready to move away from your family or if you’d prefer a job that provides more opportunities for advancement within your company, there are other options available. You can ask for a promotion to keep your current job but have it moved closer to home. Your boss may be willing to relocate you instead of hiring another person who would have conflicting priorities because they must still report back to their current office. Another option is telecommuting through the Internet or through telephone conferencing technology. This allows people to work at home or in satellite offices.

Ruby

Environment specific files and gitignore

I love my Mac for doing development! Textmate and Passenger make it my all-time favorite environment to develop Ruby / Rails in. It does have some very specific “junk” files I don’t want in my git, though.

In the beginning I would include all those files in every project’s .gitignore file. This worked since all my colleagues also work on a Mac with Passenger & TextMate. Recently I’ve come across people with different setups, which made the project’s .gitignore look like this:

.DS_Store
Thumbs.db
tmp/restart.txt
.idea
.todo
.bundle
.rake_tasks~

After some searching I found you can easily setup a global .gitignore which ignores your environment specific files. Doing so is easy:

# ~/.gitignore
.DS_Store
tmp/restart.txt
.rake_tasks~
.idea

And added this to my global git config

git config --global core.excludesfile ~/.gitignore 

This all makes your .gitignore file much cleaner and more relevant for the project itself.

Ruby and Rails beginner talk

Last night I gave a talk for Zeus about Ruby and Rails, talking about Ruby fundamentals and a short intro to the Rails philosophy and MVC.

I don’t know if you’ll be much with the slides without hearing the talk, but you can find them on http://defv.be/ruby.and.rails.pdf.

If you want to see the entire presentation you should come to ArrrrCamp, where I’ll be giving it again.

Autoload JQuery Plugins

Rails has the convenient helper javascript_include_tag where you can give up :default, which automatically loads prototype / effects, or with the jrails plugin adds jquery, jquery-ui and jrails.

But when using jQuery you want to use more than those files, you want to use jQuery plugins, or write your own, all in small .

Loading this can be a pain in the ass. Thats why I wrote this little initializer which adds everything in public/javascripts/jquery/*.js to the defaults.

# config/initializers/add_jquery_to_defaults.rb
Dir[File.join(ActionView::Helpers::AssetTagHelper::JAVASCRIPTS_DIR,'jquery','*.js')].each do |js|
  ActionView::Helpers::AssetTagHelper.register_javascript_include_default "jquery/#{File.basename(js)}"
end

Custom ActiveRecord timestamps

Some legacy databases have already defined their own created_at or updated_at fields. They can be easily filled in with ActiveRecord before_save filters, but after implementing this behaviour a few times the urge arose to write something reusable, so I created the custom_timestamps plugin.

With custom_timestamps you can easily define the columns you want to be updated on creation/change

class LegacyModel < ActiveRecord::Base
  set_create_column :creation_time
  set_update_column :change_time
end

The plugin can be found on github.

ArrrrCamp Belgium

We have been talking between ourselves about hosting a Belgian Ruby conference since the last Railsconf Europe, and we have finally decided to proceed with the idea. Colleague Joren put things in motion and today we’re proud to announce Arrrrcamp, which stands for “About Ruby, Rails, Radiant and Rum Camp”.

The event will take place on friday, May 8th, in Ghent, Belgium. The idea is to have a barcamp-like organisation of talks, where everybody is encouraged to participate by either doing talks, taking pictures, do some hacking, … You can read all about the event on the website.

Application-wide timeranges

In some applications you need to work with time-ranges a lot. Displaying todays messages, a count of all messages that were posted this month, or last month, … ActiveRecord has pretty good support for times and ranges, so you could do it the default way.

Message.find(:all, :conditions => {:created_at => Time.now.beginning_of_month..Time.end_of_month})

And although this works perfectly it’s not very easy on the eyes. It’s also not very DRY since I need this on a lot of models. It’d be a lot better if I could have it in a scope, like this

Message.in(:this_month)

So how do we achieve this?

In our config/initializer folder we have a file called timeranges.rb.

# timeranges.rb
TimeRanges = {
  :today      => lambda { Time.now.beginning_of_day..Time.now.end_of_day },
  :yesterday  => lambda { 1.day.ago.beginning_of_day..1.day.ago.end_of_day },
  :this_week  => lambda { Time.now.beginning_of_week..Time.now.end_of_week },
  :last_week  => lambda { 1.week.ago.beginning_of_week..1.week.ago.end_of_week},
  :this_month => lambda { Time.now.beginning_of_month..Time.now.end_of_month },
  :last_month => lambda { 1.month.ago.beginning_of_month..1.month.ago.end_of_month }
}

Which gives us a constant TimeRanges we can use all over the application. So in our Message we define the named_scope in

class Message < ActiveRecord::Base
  named_scope :in, lambda { |period| 
      :conditions => {:created_at => TimeRanges[period].call}
  }
end

Now we could even make this more DRY and make a module that defines the named_scope when it’s included, but in my application I had a lot of different use-cases for the TimeRanges, and didn’t really need the scope a lot. Leave me a note if you want it in a module but don’t know how to, else it’s an exercise for the interested and easily challenged reader 😉

Testing Forgery Protection

Try to follow here:

I needed to test 1 controller to see if he was not protected from forgery protection, because requests to that controller come from an external source.

So basically I need to test if my code has

skip_before_filter :verify_authenticity_token

In the test environment, the authenticity_token check is disabled. You can re-enable it in your test like this:

class AccountsControllerTest < ActionController::TestCase
  def setup
    super
    AccountsController.allow_forgery_protection = true # Make sure we have forgery protection before filter turned off
  end
end

When you do a post and you haven’t skipped the filter, the test will fail.

session_lifetime plugin

One of the things I take for granted on the internet is session expiry. I’m used to the fact that if I’m not active for a certain amount of time, I automatically get logged out. This happens with my Online Banking, with ordering tickets online, …. Most information-critical applications have this.

Because of that, I was surprised that Rails doesn’t have this functionality on board. There is no way to set an expiry date on your session. I googled a bit and stumbled upon the dynamic session exp plugin. This gives you the possibility to expire your session through the cookie’s expires-flag.

An example

# in environment.rb
CGI::Session.expire_after 1.day

This plugin worked fine until I wanted to send a message to the webuser, informing him why this happened. Because we’re working with the expire-setting in a cookie, this isn’t possible. Because of that, I wrote my own plugin that gave me that possibility.

With session_lifetime you can set after how much time of inactivity your session should expire, you can execute an action when the session expires, and you can set where to redirect_to after session expiry.

An example

class ApplicationController << ActionController::Base
  expires_session :time => 2.hours, :redirect_to => '/login'

  protected
  def on_expiry
    flash[:notice] = "Your session has been expired, and you have been logged out."
  end
end

More information can be found on github.

Missing something?

I wrote this plugin to solve the problems I had with default Rails session handling. If you have an additional need which you think would be great for this plugin, give me a shout at [email protected], or through GitHub, and I’ll be more then happy to implement your proposal.

RailsXLS Revived

RailsXLS is a plugin to generate Excel files from a .rxls view. It uses a Java Bridge to talk to the Jakarta POI library. I’ve used this plugin in a few projects and it works great for generating .xls files.

On a recent project I once again needed an “Export to Excel” feature. The project is on Rails Edge, and apparently there were some changes to how TemplateHandlers are handled since the plugin was written. I dove into the code and recreated the plugin for Rails Edge / 2.2.

You can find the new plugin on github

It’s usage is quite easy:

# in your environment.rb
Mime::Type.register "application/excel", :xls

# in controller
def index
  @clients = Client.all
  respond_to do |speaks|
    speaks.html
    speaks.xls { render :layout => false }
  end
end

# in index.xls.rxls
sheet = workbook.createSheet("Client List")

@clients.each_with_index do |client, index|
  row = sheet.createRow(index)
  row.createCell(0).setCellValue(client.id)
  row.createCell(1).setCellValue(client.name)
end

As you can see there are still some rough patches in the view. I’m working on a wrapper around this, so all obvious tasks can be easily performed.

Any comments/suggestions for the plugin are very welcome! A big thanks to Venkata Subramaniyan for writing the initial plugin, which can be found here

Do Not Forget: NamedScope and dates

One of the scopes I had in a project was from_this_month

class Transaction
  named_scope :from_this_month, :conditions => {:created_at => Time.now.beginning_of_month..Time.now}
  ...
end

Which worked great to know all transactions from a user in a certain month. I could do current_user.transactions.from_this_month. When I tested this in developer mode all went well.. Production, however, didn’t work at all.

As we all know, Developer mode reloads classes every time you make a request. Production mode obviously doesn’t, so in Production, the first time you load the page you get a correct time-scope, if you do it a day later, however, the scope is still the same of yesterday. This can be solved with a proc or a lambda, which will get called on each request!

So, just to make sure I never forget, Use a lambda!

class Transaction
  named_scope :from_this_month, lambda { {:conditions => {:created_at => Time.now.beginning_of_month..Time.now}} }
  ...
end

Pros and Cons

A recent commit to the Rails github repository had quite some comments. In one of the tests there was the string:

    topic = @target.new(:title => "The pros and cons of programming naked.")

After which Mislav Marohnić asked the obvious question:
Commit 4d9a7ab5f5c28820e0b076f9ca44bdd20e19e6ea to rails's rails — GitHub

After which we now have a pretty nice list of all the pro’s and cons of naked programming!

Refactoring: Implementing filtering

For a project at Openminds we needed an implementation for filtering some data from a list with the aid of checkboxes. Our first solution looked like this:

def index
  session[:order_filter] = params[:filter] if params[:filter] 
  session[:order_filter] ||= { :active => '1', :inactive => '1' } 

  if session[:order_filter][:active] == '0' && session[:order_filter][:inactive] == '0'
    @orders = []
  elsif session[:order_filter][:active] == '0'
    @orders = @user.orders.find(:all, :conditions => {:state => 'active'})
  elsif session[:order_filter][:inactive] == '0'
    @orders = @user.orders.find(:all, :conditions => {:state => 'inactive'})
  else
    @orders = @user.orders.find(:all)
  end
end

So this code takes the filter-parameters from params, or initializes them from defaults, and then does the correct finds.

In the next iteration, I stumbled onto this code and thought to myself “This can be done better”. After making sure the index action was sufficiently covered with tests, I had a go at it, this is what I came up with:

def list
  if filter.active? && filter.inactive?
      @orders = @user.orders.all
  elsif filter.active?
     @orders = @user.orders.active
  elsif filter.inactive?
    @orders = @user.orders.inactive
  else
    @orders = []
  end
end

protected
def filter
  return @filter if @filter
  session[:order_filter] = params[:filter] if params[:filter]
  session[:order_filter] ||= { :active => '1', :inactive => '1' }

  @filter = SearchFilter.new("Order", session[:order_filter])
end
helper_method :filter

# search_filter.rb
class SearchFilter
  attr_reader :name

  def initialize name, hash
    @name = name
    hash.each do |key, value|
      instance_eval <<METHOD
        def #{key}?
          #{value} == 1
        end
METHOD
    end
  end
end

This code is more readable in my opinion. I extracted the session-storing and parameter-juggling to the filter-method, which then returns a SearchFilter object. Thanks to SearchFilter I can now query filter for set values in a nice way. I can also call filter in my views, which is nicer then calling session[:order_filter][:active]. I also used named_scope instead of doing the finds manually, which improves readability a lot too!

How would you refactor this?

acts_as_state_machine with auto named_scope powers

Rails 2.1 (Soon to be released?) brings us integrated named_scope‘ing. I’ve already mentioned named_scope here and there, and you can find a complete writeup on Ryan Daigle’s Blog

While working on projects on Rails Edge, we used to have the same pattern over and over.

class Mail < ActiveRecord::Base
  include AASM

  aasm_state :created
  aasm_state :sending
  aasm_state :sent
  aasm_state :failed
  aasm_state :delayed

  named_scope :created, :conditions => {:status => 'created'}
  named_scope :sending, :conditions => {:status => 'sending'}
  named_scope :sent, :conditions => {:status => 'sent'}
  named_scope :failed, :conditions => {:status => 'failed'}
  named_scope :delayed, :conditions => {:status => 'delayed'}
end

For each state we had, we created a named_scope, because it is so great and easy to be able to say Mail.failed.each .... However, this isn’t really DRY, and we can see a clear pattern here. When you think about it, you really should have a scope for every state you define. So I forked from AASM on github and started hacking away.

The result:

class Mail < ActiveRecord::Base
  include AASM

  aasm_state :created
  aasm_state :sending
  aasm_state :sent
  aasm_state :failed
  aasm_state :delayed
end

...
>> Mail.failed
=> []
>> Mail.sent
=> [#<Mail id: 1, email: "[email protected]", content: "hallo", :aasm_state: "sent", created_at: "2008-05-21 15:39:38", updated_at: "2008-05-21 15:39:38">, #<Mail id: 2, email: "[email protected]", status: "sent", created_at: "2008-05-21 15:39:39", updated_at: "2008-05-21 15:39:39">]

You can find my named_scope enabled AASM on github. At the moment only the master branch has been patched with my functionality, I’ll do the no_aasm_prefix branch somewhere this evening / tomorrow. Let me know if you’re using it, and what could be better
This has all been implemented in the AASM Core now.

For those interested in the code, this is the bit that does the magic.

module AASM::NamedScopeMethods
  def self.add_named_scope base
    # Don't add unless it's a class which understands `named_scope`
    return unless base.respond_to? :named_scope

    base.extend AASM::NamedScopeMethods::ClassMethods
    base.class_eval do
      class << self
        alias_method :aasm_state_without_named_scope, :aasm_state
        alias_method :aasm_state, :aasm_state_with_named_scope
      end
    end
  end

  module ClassMethods
    def aasm_state_with_named_scope name, options = {}
      aasm_state_without_named_scope name, options

      self.named_scope name, :conditions => {self.aasm_column => name.to_s} unless self.scopes.include?(name)
    end
  end
end

Gotcha

While testing the plugin we found out 1 gotcha to this: do not define a aasm_state :new, because this will override the constructor of the class, and you’ll lose all creating-functionality.

Update

This is now default AASM behaviour.

Savon

I’ve been struggling for the past few hours trying to get the VIES service of the European Union to work with Savon (Ruby SOAP library) in production. It worked in development but timed out in production, and I soon figured out it was only happening when IPv6 was enabled.

The response I would get when requesting the WDSL on IPv6 was a proxy timeout


* About to connect() to ec.europa.eu port 80 (#0)
*   Trying 2a01:e0b:1:143:62eb:69ff:fe8f:16e6... * Connected to ec.europa.eu (2a01:e0b:1:143:62eb:69ff:fe8f:16e6) port 80 (#0)
> GET /taxation_customs/vies/checkVatService.wsdl HTTP/1.1
Host: ec.europa.eu
Accept: */*

* HTTP 1.0, assume close after body
< HTTP/1.0 503 Service Unavailable
< Cache-Control: no-cache
< Connection: close
< Content-Type: text/html
< Content-Length: 310
< 
* Excess found in a non pipelined read: excess = 20, size = 310, maxdownload = 310, bytecount = 0
* Expire cleared
* Closing connection #0
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Error</title>
</head>
<body>
<h1>Erreur 503</h1>
<h2>Erreur proxy ipv6</

Yet, when I would do the same request with the curl command-line tool I got the correct WSDL. The only difference was the User-Agent, and apparently that was the issue! When I added something in the User-Agent header, the request fell trough. So I changed my SOAP setup to this:

Savon::Client.new do
  wsdl.document = 'http://ec.europa.eu/taxation_customs/vies/checkVatService.wsdl'
  wsdl.namespace = 'urn:ec.europa.eu:taxud:vies:services:checkVat:types'

  http.headers['User-Agent'] = 'Factr Soap Client'
  http.open_timeout = 2
  http.read_timeout = 2
end

MySQL password hashing in Ruby

An old database used MySQL’s PASSWORD() hashing functionality for storing user credentials. We’re creating a Ruby app now to interface with that database, and wanted to hash the password in ruby. After looking at the code it looked like they just SHA1 hash the password twice and prepend a *. Implementation in Ruby is easy:

require 'digest/sha1'

def hash_mysql_password pass
  "*" + Digest::SHA1.hexdigest(Digest::SHA1.digest(pass)).upcase
end

Which gives us in MySQL

mysql> SELECT PASSWORD('foo');
+-------------------------------------------+
| PASSWORD('foo')                           |
+-------------------------------------------+
| *F3A2A51A9B0F2BE2468926B4132313728C250DBF | 
+-------------------------------------------+

And in Ruby

>> hash_mysql_password 'foo'
=> "*F3A2A51A9B0F2BE2468926B4132313728C250DBF"

Inlining CSS in ActionMailer 3 (Rails 3.0)

As most of you already know, a bunch of online mail readers (like Hotmail, Gmail, …) don’t handle stylesheets very well, they prefer inline styling (

TamTam is a gem created by Dave Hoover and Brian Tatnall that does all the dirty work for us. Before Rails 3 there was a plugin called inline_css (by the same authors) that used TamTam to automatically inlined all mails sent by ActionMailer. Since Rails 3, however, the ActionMailer internals have changed, and the plugin stopped working.

For my own use I created a module called InlineCss that I include in the mailers I need inlining for. This is the code:

module InlineCss
  def render(*args)
    if (template = args.first[:template]) && template.mime_type.html?
      # Be warned, this code expects a <style> tag in the head of your layout.
      TamTam.inline(:document => super)
    else
      super
    end
  end
end

This code sees if I am working with a template and if that template has a HTML MIME-type, it inline’s it with TamTam.

In my mailers I just include it. If you want to have this in all mailers, just add an initializer that includes InlineCss in ActionMailer::Base, and it should work

Radiant 0.7.x and Ruby 1.8.4

A client of ours complained that Radiant 0.7.1 was not working out of the box on one of our shared servers. When running the radiant command he got an error:

/usr/lib/ruby/gems/1.8/gems/radiant-0.7.1/vendor/rails/railties/lib/initializer.rb:199:in `set_load_path': undefined method `load_paths' for nil:NilClass (NoMethodError)
  from /usr/lib/ruby/gems/1.8/gems/radiant-0.7.1/vendor/rails/railties/lib/initializer.rb:97:in `run'
  from /usr/lib/ruby/gems/1.8/gems/radiant-0.7.1/lib/radiant/initializer.rb:101:in `run'
  from /usr/lib/ruby/gems/1.8/gems/radiant-0.7.1/bin/../config/boot.rb:72:in `load_initializer'
  from /usr/lib/ruby/gems/1.8/gems/radiant-0.7.1/bin/../config/boot.rb:90:in `load_initializer'
  from /usr/lib/ruby/gems/1.8/gems/radiant-0.7.1/bin/../config/boot.rb:61:in `run'
  from /usr/lib/ruby/gems/1.8/gems/radiant-0.7.1/bin/../config/boot.rb:19:in `boot!'
  from /usr/lib/ruby/gems/1.8/gems/radiant-0.7.1/bin/../config/boot.rb:161
  from /usr/local/lib/site_ruby/1.8/rubygems/custom_require.rb:31:in `require'
  from /usr/lib/ruby/gems/1.8/gems/radiant-0.7.1/bin/radiant:3
  from /usr/bin/radiant:19

It worked fine on our other servers, as well as on our local machines, the only thing that was different was the ruby version, which was 1.8.4 on that specific server. Apparently that version handles super a bit different. The solution was to change 1 line in /usr/lib/ruby/gems/1.8/gems/radiant-0.7.1/lib/radiant/initializer.rb:

# In /usr/lib/ruby/gems/1.8/gems/radiant-0.7.1/lib/radiant/initializer.rb line 101:
-     super
+     super(command, configuration)

Using Datamapper On Legacy Databases

Yesterday I had to map a legacy database schema to some Ruby classes. Just before that I had been looking into the advantages of DataMapper, and it looked like the perfect match for my current “challenge”.

from the DataMapper site:

DataMapper only issues updates or creates for the properties it knows about. So it plays well with others. You can use it in an Integration Database without worrying that your application will be a bad actor causing trouble for all of your other processes.

The system

The system is running with 2 databases. One database holds all the information for the legacy app, the other database holds all information for system management.

mysql app
mysql> desc cpClients;
+--------------+--------------+------+-----+---------+----------------+
| Field        | Type         | Null | Key | Default | Extra          |
+--------------+--------------+------+-----+---------+----------------+
| clientID     | int(255)     | NO   | PRI | NULL    | auto_increment | 
| login        | varchar(255) | NO   | UNI |         |                | 
| pass         | varchar(255) | NO   |     |         |                | 
| type         | int(2)       | NO   |     | 0       |                | 
| traffic      | bigint(255)  | NO   |     | 0       |                | 
<snip>
| VAT          | varchar(255) | YES  |     | NULL    |                | 
+--------------+--------------+------+-----+---------+----------------+
mysql> desc cpURL;
+----------+--------------+------+-----+---------+-------+
| Field    | Type         | Null | Key | Default | Extra |
+----------+--------------+------+-----+---------+-------+
| url      | varchar(255) | NO   | PRI |         |       | 
| clientID | int(255)     | NO   |     | 0       |       | 
+----------+--------------+------+-----+---------+-------+
> exit
mysql management
mysql> desc ftp_users;
+--------------+------------------+------+-----+-------------------+-------+
| Field        | Type             | Null | Key | Default           | Extra |
+--------------+------------------+------+-----+-------------------+-------+
| username     | varchar(60)      | NO   | PRI | NULL              |       | 
| password     | varchar(30)      | YES  |     | NULL              |       | 
<snip>
| homedir      | text             | YES  |     | NULL              |       | 
| shell        | varchar(15)      | NO   |     | /bin/false        |       | 
+--------------+------------------+------+-----+-------------------+-------+

One Client has many URL’s, One client also has many ftp_users, but the link in that can’t be captured in a simple has many relationship.

Solving it with DataMapper

Setting up the connections

Setting up 2 connections to the databases was quite easy and well documented. I chose the app database to be the default connection, and management as another.

DataMapper.setup(:default, 'mysql://localhost/app')
DataMapper.setup(:management, 'mysql://localhost/management')
Having different database names

The first problem I had was that I wanted the cpClient table to be mapped to the User class, and cpURL to be mapped to a Domain class. This can be solved with storage_names.

class User
    include DataMapper::Resource
    storage_names[:default] = 'cpClients'
end

class Domain
    include DataMapper::Resource
    storage_names[:default] = 'cpURL'
end
Defining primary keys

Defining the primary key of my cpURL table was quite easy since DataMapper does natural keys out of the box.

class Domain
  include DataMapper::Resource
  storage_names[:default] = 'cpURL'

  property :url, String, :key => true
end

Defining the primary key of the cpClients table was a tad more difficult since it was poorly documented. I wanted the property to be called ID, but it should still use clientID in the database. The magic option to this is :field, which allows you to set a custom field for a propery.

class User
    include DataMapper::Resource
    storage_names[:default] = 'cpClients'

    property :id,                    Serial, :field => 'clientID'
end
Defining associations

The hardest part was defining associations. When I’d just define them with has n without extra options, DataMapper would look for user_id, so I’d have to tell which key was used. Since it wasn’t very well documented I had some failed attempts

has n, :domains, :child_key => 'clientID'
# => +options[:child_key]+ should be Array, but was String (ArgumentError)

has n, :domains, :child_key => ['clientID']
# => ArgumentError: +name+ should be Symbol, but was String 

has n, :domains, :child_key => [:clientID]
# => MysqlError: Unknown column 'client_i_d' in 'field list' (mysql_error_code=0001)

So I need to use a symbol, but apparently DataMapper does some automatic magic to translate keys. When you have a key like me you can disable this magic by changing field_naming_convention’s proc to your own. In the proc we return the stringified value’s name (to_s is needed because the key is given as a symbol)

repository(:default).adapter.field_naming_convention = lambda { |value| value.name.to_s }

And then the association worked. Do note the :child_key option needs to be set at both sides.

class User
  has n, :domains, :child_key => [:clientID]
end

class Domain
  belongs_to :user, :child_key => [:clientID]
end
Setting models to automatically connect to another database

The FtpUser model automatically needs to connect to the :management database, and there doesn’t seem to be a function to set this. If you temporarily want to connect to another database you can do it with the repository command.

repository(:management) { FtpUser.first }

However, if you want a model to always connect to a database other then the default, defining self.default_repository_name with the correct repository works very well. (Databases are referred to as repositories)

class FtpUser
  include DataMapper::Resource

  def self.default_repository_name
      :services
  end
end

All of this was needed to get my legacy database mapped, I hope some of you find this information useful. If you see things I can do better / different, do let me know in the comments. I’ve only used DataMapper for about 2 hours so some of my assumptions may be way of.

Our partners

self. works_with_ruby?