All posts by adminworks

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 to bet on sports with mobile apps

There is no doubt that the way we bet on sports has changed dramatically in recent years. With the advent of mobile betting apps, it is now possible to place bets on the go, from anywhere in the world. But how do you go about using these apps to win bets? In this article, we will provide a step-by-step guide on how to use betting applications to your advantage.

Features of mobile betting apps

Before you start betting on sports via a mobile app, it is important to understand how the process works. Basically, you need to download an Android apk file that offers mobile betting from https://redraidersoftball.org/ and install it, open an account with a bookmaker, deposit some money into that account, and then start placing bets.

The beauty of mobile betting apps is that you can place bets anywhere, anytime. All you need is an internet connection and a mobile device (smartphone or tablet). Most mobile betting apps offer a wide range of betting options, including head-to-head bets, over/under bets, and even live betting.

How to place bets via mobile apps

To create a profile at the betting application, you need to provide your name, email address, date of birth and country of residence. You will also need to choose a username and password. Once you have registered for an account with a bookmaker that offers a mobile betting app, the next step is to deposit some money into that account. This can be done in a number of ways, including via a credit or debit card, through an e-wallet, or by transferring money from your bank account.

After the deposit, you can start betting. To place a bet, you first need to select the sport and the event that you want to bet on. You can then select the amount that you want to bet and the odds. Finally, you need to click on the ‘Place Bet’ button. Your bet will then be placed and you will see the current odds for that bet.

How to win bets

When you win a bet, you will usually be paid out in the form of a cash prize. The amount you win will depend on the odds of the bet you placed. To win mobile bets, you need to make sure you are betting on events where the odds are in your favour. You can do this by checking the odds offered by different bookmakers and then choosing the bookmaker that offers the best odds.

You should also make sure you understand the rules of the sport you are betting on. This will help you to make informed predictions about the outcome of events.

How to withdraw

To withdraw your winnings, you need to first click on the ‘Withdraw’ button and then select your preferred payment method. You will then need to enter your bank account number or your card number and the amount that you want to withdraw. You will also need to enter the security code for your card. Once you have entered all the information, click on the ‘Submit’ button.

How to get bonuses for mobile betting

Many mobile betting apps offer bonuses for betting on sports. These bonuses can be a percentage of your deposit, a free bet, cash bonuses, or even extra loyalty points. To get a bonus, you first need to create an account and then deposit some money. Once you have deposited money, you need to click on the ‘Claim Bonus’ button and follow the instructions.

Conclusion

So, there you have it – a step-by-step guide on how to use mobile betting apps to your advantage. By following the instructions in this guide, you can maximize your chances of winning bets and making profits.

How well does the Mostbet app works

Mobile betting has become increasingly important and popular in recent years. Accordingly, many bookmakers have created mobile betting concepts. At Mostbet, you can bet via mobile and tablet using the official. 

On this page, we take a close look at how well betting works at Mostbet app and whether you can also use the bonus on the go. We will explain how you can place bets on the go, what the mobile betting offer looks like and how user-friendly the bookmaker’s mobile site is.

What are the advantages of the Mostbet app?

With the Mostbet app you can easily place bets via smartphone and tablet. You don’t need a browser for this. You simply open the next website https://ticketyboo-apps.com/bookmaker/mostbet-app/ with your portable device via your preferred browse. Then, click on the download button and install the apk.

The main advantage of the Mostbet application is its easy usability. You can also deposit with the most popular payment methods in Bangladesh and get your winnings as quickly as possible.

What does the betting offer of the Mostbet App look like?

The Mostbet betting app is exactly the same as in the classic desktop version. Therefore, you can pick out your events in the very wide betting offer with the huge markets even with your cell phone and tablet. 

Mostbet offers around 40 different sports, and you can also bet on e-sports, politics, lotto, weather and some more “exotic disciplines” such as Pesäpallo, Aussie Rules and Keirin. In addition, you can expect a wealth of betting opportunities. In the English Premier League, for example, you have more than 1500 betting markets in which you can let off steam. 

The live betting center at the Mostbet app – like at the partner sites – is also lavishly equipped. Betting professionals and fans of marginal sports will definitely get their money’s worth at this bookmaker.

How to bet?

Here you will find a step-by-step guide on how to place successful bets at Mostbet app.

  1. Log in to your profile
  2. Choose the event you want to bet on
  3. You can use the search or click on the sport and then on the event
  4. When you click on the event, the betting market will be opened
  5. Click on the odds you want to play to get them on the betting slip
  6. The betting slip opens at the bottom of the screen – go to “To betting slip
  7. Choose between single, combined and system bets
  8. Enter the stake and confirm with “Place bet”.

How user-friendly is the Mostbet mobile app?

The structure of the Mostbet mobile application is quite similar to the partner sites. Even beginners should be able to quickly find their way around the site, even if the offer seems a bit confusing and cluttered at first glance. The large betting program with the many odds could certainly have been arranged a bit more orderly. 

The mobile version of Mostbet is basically built like an app, so it makes an additional program superfluous. In the header, you can quickly switch between “Sports” – the pre-match sports betting -, “Live” – the live betting – and the casino offer. Below that, you scroll through all the sports that the bookie can offer. Next come the highlights. A plus is that the bookmaker has dispensed with flashing banners and slideshows.

Can you get Mostbet bonus?

New betting providers usually try to attract new customers with welcome offers. The bookmaker Mostbet goes exactly this way. This new customer promotion is the classic version of the 100% deposit bonus up to € 100.

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.

How to download Betway App for iOS and Android

Betway is one of the major British bookmakers. The house can look back on a success story of more than ten years. The mobile offer has also been significantly expanded. We have taken a look at it for you. If you are interested in the Betway app, you should definitely read on.

Betway App for iOS and Android

Basically, Betway offers both a webapp and downloadable apps for iOS and Android. You can use the webapp or native application with any smartphone or tablet. You don’t have to do anything more than enter the address into the designated field of your mobile browser. Thanks to the Responsive Design, the webpage should always be displayed in the perfect size ratio.

With the iOS Betway app, “only” sports betting is possible. Like the iOS application, the Android app is also limited to sports betting. If you are only interested in sports betting, the downloadable app is fully sufficient.

Download Betway app safely

You can get the iOS app for iPhone and iPad from Apple’s AppStore. The AppStore automatically detects whether you visit it with smartphone or tablet and selects the appropriate app.

For all Android owners, the app is available in the bookmaker’s mobile homepage or here: https://onlinebettingapp.in/bookmakers/betway-app/. Furthermore, however, you have to allow downloads from unknown sources in the settings of your device in order to be able to install the app after downloading it.

Registration

On the Betway app you can click on the big button “Register Now”. The registration form is only one-sided, but very long. At the very end you have to tick the box that you want to receive the welcome bonus offer, otherwise you will miss out. Filling out the form only takes a few minutes. You will be asked only the information that you probably already know from other bookmakers – so name, address, username, password, etc.

Betway Mobile betting program review

At the time of our test, there were just over 30 categories to be found in Betway’s betting program. Thousands of individual bets are waiting for you here. You will find most of the offers in soccer, which should suit most of you. There are also numerous offers for the competitions. You will get your money’s worth if you are interested in the professional leagues or, for example, the cup.

However, we would like to draw your attention to the Betway Boosts category. In this category, Betway has compiled bets across all sports in which you can earn an attractive sports betting bonus. This category rounds off the very positive overall impression that we have gained from the Betway app.

Advantages / Disadvantages

We have taken a closer look at the advantages and disadvantages of the Betway app for you.

Advantages of the Betway App:

  • Simple menu and imaginative design (just look at the icons for the sports).
  • All desktop functions also mobile.
  • App runs very smoothly
  • You can also get the attractive Betway bonus via mobile.

Disadvantages of the Betway app:

  • Settings need to be changed for Android app

Conclusion

Our conclusion on the Betway app: if you like to play on mobile, want to use a technically mature app that has a large betting program and a good worldwide languages output, as well as attractive bonuses, you should reach for Betway. Only the small hurdle that you first have to change the settings for installing the Android app as a small point of criticism.

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"