repo
string | commit
string | message
string | diff
string |
---|---|---|---|
jstorimer/sinatra-shopify
|
5258078cb35ee96bc400a99fbef34e364f6c7c14
|
Tidy up Shopify extension
|
diff --git a/lib/sinatra/shopify.rb b/lib/sinatra/shopify.rb
index a87797b..5d0f374 100644
--- a/lib/sinatra/shopify.rb
+++ b/lib/sinatra/shopify.rb
@@ -1,62 +1,78 @@
require 'sinatra/base'
-require 'active_support'
-require 'active_resource'
-
-gem 'shopify_api'
require 'shopify_api'
module Sinatra
module Shopify
module Helpers
def current_shop
session[:shopify]
end
def authorize!
redirect '/login' unless current_shop
- ActiveResource::Base.site = session[:shopify].site
+ ShopifyAPI::Base.site = session[:shopify].site
end
def logout!
session[:shopify] = nil
end
end
def self.registered(app)
app.helpers Shopify::Helpers
app.enable :sessions
+ app.template :login do
+ <<-SRC
+ <h1>Login</h1>
+
+ <p>
+ First you have to register this app with a shop to allow access to its private admin data.
+ </p>
+
+ <form action='/login/authenticate' method='post'>
+ <label for='shop'><strong>The URL of the Shop</strong>
+ <span class="hint">(or just the subdomain if it's at myshopify.com)</span>
+ </label>
+ <p>
+ <input type='text' name='shop' />
+ </p>
+ <input type='submit' value='Authenticate' />
+ </form>
+ SRC
+ end
+
ShopifyAPI::Session.setup(:api_key => ENV['SHOPIFY_API_KEY'], :secret => ENV['SHOPIFY_API_SECRET'])
app.get '/login' do
erb :login
end
app.get '/logout' do
logout!
redirect '/'
end
app.post '/login/authenticate' do
redirect ShopifyAPI::Session.new(params[:shop]).create_permission_url
end
app.get '/login/finalize' do
shopify_session = ShopifyAPI::Session.new(params[:shop], params[:t])
if shopify_session.valid?
session[:shopify] = shopify_session
return_address = session[:return_to] || '/'
session[:return_to] = nil
redirect return_address
else
redirect '/login'
end
end
end
end
register Shopify
end
|
jstorimer/sinatra-shopify
|
fccb01c0ec5e139c66db0ec900d890b97a13e959
|
Adding gemspec and gemifying this
|
diff --git a/LICENSE b/LICENSE
index 8a4561a..5850866 100644
--- a/LICENSE
+++ b/LICENSE
@@ -1,20 +1,20 @@
-Copyright (c) 2009 Jesse Storimer
+Copyright (c) 2011 Jesse Storimer
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOa AND
NONINFRINGEMENT. IN NO EVENT SaALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
\ No newline at end of file
+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/README.textile b/README.md
similarity index 84%
rename from README.textile
rename to README.md
index 2d76255..bd2b970 100644
--- a/README.textile
+++ b/README.md
@@ -1,43 +1,45 @@
-h1. Sinatra-Shopify: A classy shopify_app
+Sinatra-Shopify: A classy shopify_app
+====================================
-This is a basic sinatra app that allows you to work with the "Shopify API":http://shopify.com/developers. It's basically just a port of the "shopify_app":http://github.com/Shopify/shopify_app rails plugin to sinatra.
+This is a Sinatra extension that allows you to work with the "Shopify API":http://shopify.com/developers. It's basically just a port of the "shopify_app":http://github.com/Shopify/shopify_app rails plugin to sinatra.
-h2. Why?
+== Why?
I have been "having fun working on Shopify apps":http://www.jstorimer.com/blogs/my-blog/1133402-shopify-api-extensions lately, but I needed a simpler way than always generating a new rails app, new controllers, etc., for every little idea.
Rails is great, but most of the "Shopify apps":http://apps.shopify.com that I have come up with are one page apps, maybe two or three pages. The point is, I don't need a controller for that, I don't need the 63 files or however many the rails generator generates for me.
Sinatra is most awesome when you are working on a small app with just a few routes. You can clone this app and use it as a starting point for a shopify_app. All of the authentication logic/routes are in the lib folder, so they don't pollute the code of your app.
So in app.rb, you just have to worry about the functionality of your app.
-h2. Usage
+== Usage
-The fastest way to get this thing running:
+Installable from rubygems as 'sinatra-shopify'.
+
+The current implementation for authentication is to add the @authorize!@ method at the top of any routes that you want to be authenticated, like so:
+
+```ruby
+get '/sensitive_data' do
+ authorize!
+
+ # then do the sensitive stuff
+end
+```
+
+Example
+======
+
+This repo includes an example Sinatra app. The fastest way to get it running:
* @git clone git://github.com/jstorimer/sinatra-shopify@
* @cd sinatra-shopify@
* @heroku create@ (make sure that you remember the name of your app as you will need that later)
* visit the "Shopify Partners area":http://app.shopify.com/services/partners
* Sign up for an account if you don't already have one
* Log in to your Shopify partners account
* Create a new application.
* Make sure that the Callback URL is set to http://_yourapp_.heroku.com/login/finalize
* In the lib/sinatra/shopify.yml file replace API_KEY and SECRET with the Api Key and Secret that you just got from the Shopify Partners area
* @git push heroku master@
* @heroku open@
-
-The current implementation for authentication is to add the @authorize!@ method at the top of any routes that you want to be authenticated, like so:
-
-<pre><code>
-get '/sensitive_data' do
- authorize!
-
- # then do the sensitive stuff
-end
-</code></pre>
-
-h2. Disclaimer
-
-I am by no means a sinatra expert, this is really my first experience with sinatra. So if you see anything that could be done better, fork away.
\ No newline at end of file
diff --git a/lib/sinatra/shopify.rb b/lib/sinatra/shopify.rb
index 6698f62..a87797b 100644
--- a/lib/sinatra/shopify.rb
+++ b/lib/sinatra/shopify.rb
@@ -1,65 +1,62 @@
require 'sinatra/base'
require 'active_support'
require 'active_resource'
gem 'shopify_api'
require 'shopify_api'
module Sinatra
module Shopify
module Helpers
def current_shop
session[:shopify]
end
def authorize!
redirect '/login' unless current_shop
ActiveResource::Base.site = session[:shopify].site
end
def logout!
session[:shopify] = nil
end
end
def self.registered(app)
app.helpers Shopify::Helpers
app.enable :sessions
- # load config file credentials
- config = File.dirname(__FILE__) + "/shopify.yml"
- credentials = YAML.load(File.read(config))
- ShopifyAPI::Session.setup(credentials)
+ ShopifyAPI::Session.setup(:api_key => ENV['SHOPIFY_API_KEY'], :secret => ENV['SHOPIFY_API_SECRET'])
app.get '/login' do
erb :login
end
app.get '/logout' do
logout!
redirect '/'
end
app.post '/login/authenticate' do
redirect ShopifyAPI::Session.new(params[:shop]).create_permission_url
end
app.get '/login/finalize' do
shopify_session = ShopifyAPI::Session.new(params[:shop], params[:t])
if shopify_session.valid?
session[:shopify] = shopify_session
return_address = session[:return_to] || '/'
session[:return_to] = nil
redirect return_address
else
redirect '/login'
end
end
end
end
register Shopify
-end
\ No newline at end of file
+end
diff --git a/lib/sinatra/shopify.yml b/lib/sinatra/shopify.yml
deleted file mode 100644
index be84358..0000000
--- a/lib/sinatra/shopify.yml
+++ /dev/null
@@ -1,2 +0,0 @@
-api_key: API_KEY
-secret: SECRET
\ No newline at end of file
diff --git a/sinatra-shopify.gemspec b/sinatra-shopify.gemspec
new file mode 100644
index 0000000..3bca0a9
--- /dev/null
+++ b/sinatra-shopify.gemspec
@@ -0,0 +1,17 @@
+Gem::Specification.new do |s|
+ s.name = 'sinatra-shopify'
+ s.version = '1.0.0'
+
+ s.summary = "A classy shopify_app"
+ s.description = "A Sinatra extension for working with the Shopify API. Akin to the shopify_app gem but for Sinatra"
+
+ s.authors = ["Jesse Storimer"]
+ s.email = "jesse@gmail.com"
+ s.homepage = "https://github.com/jstorimer/sinatra-shopify/"
+
+ s.files = Dir.glob('lib/**/*.rb')
+ s.files += ['README.md', 'LICENSE']
+
+ s.add_dependency 'sinatra', '~> 1.0'
+end
+
|
jstorimer/sinatra-shopify
|
c53f36dda05e2f40cb548fcdbbae9c7ec0cb9d95
|
Add auth section to README.
|
diff --git a/README.textile b/README.textile
index 59ff48b..2d76255 100644
--- a/README.textile
+++ b/README.textile
@@ -1,33 +1,43 @@
h1. Sinatra-Shopify: A classy shopify_app
This is a basic sinatra app that allows you to work with the "Shopify API":http://shopify.com/developers. It's basically just a port of the "shopify_app":http://github.com/Shopify/shopify_app rails plugin to sinatra.
h2. Why?
I have been "having fun working on Shopify apps":http://www.jstorimer.com/blogs/my-blog/1133402-shopify-api-extensions lately, but I needed a simpler way than always generating a new rails app, new controllers, etc., for every little idea.
Rails is great, but most of the "Shopify apps":http://apps.shopify.com that I have come up with are one page apps, maybe two or three pages. The point is, I don't need a controller for that, I don't need the 63 files or however many the rails generator generates for me.
Sinatra is most awesome when you are working on a small app with just a few routes. You can clone this app and use it as a starting point for a shopify_app. All of the authentication logic/routes are in the lib folder, so they don't pollute the code of your app.
So in app.rb, you just have to worry about the functionality of your app.
h2. Usage
The fastest way to get this thing running:
* @git clone git://github.com/jstorimer/sinatra-shopify@
* @cd sinatra-shopify@
* @heroku create@ (make sure that you remember the name of your app as you will need that later)
* visit the "Shopify Partners area":http://app.shopify.com/services/partners
* Sign up for an account if you don't already have one
* Log in to your Shopify partners account
* Create a new application.
* Make sure that the Callback URL is set to http://_yourapp_.heroku.com/login/finalize
* In the lib/sinatra/shopify.yml file replace API_KEY and SECRET with the Api Key and Secret that you just got from the Shopify Partners area
* @git push heroku master@
* @heroku open@
+The current implementation for authentication is to add the @authorize!@ method at the top of any routes that you want to be authenticated, like so:
+
+<pre><code>
+get '/sensitive_data' do
+ authorize!
+
+ # then do the sensitive stuff
+end
+</code></pre>
+
h2. Disclaimer
I am by no means a sinatra expert, this is really my first experience with sinatra. So if you see anything that could be done better, fork away.
\ No newline at end of file
|
jstorimer/sinatra-shopify
|
cec93e867bb55dac701cc4b05699f4e3ba7a6bdb
|
Put things back the way they were.
|
diff --git a/app.rb b/app.rb
index 2128da6..c57b01b 100644
--- a/app.rb
+++ b/app.rb
@@ -1,18 +1,20 @@
+require 'rubygems'
+require 'vendor/rack/lib/rack.rb'
+require 'vendor/sinatra/lib/sinatra.rb'
require File.dirname(__FILE__) + '/lib/sinatra/shopify'
-set :raise_errors, true
get '/' do
redirect '/home'
end
get '/home' do
authorize!
@products = ShopifyAPI::Product.find(:all, :params => {:limit => 3})
@orders = ShopifyAPI::Order.find(:all, :params => {:limit => 3, :order => "created_at DESC" })
erb :index
end
get '/design' do
erb :design
end
\ No newline at end of file
diff --git a/config.ru b/config.ru
index da5f78f..b9f5e88 100644
--- a/config.ru
+++ b/config.ru
@@ -1,6 +1,2 @@
-require 'rubygems'
-require 'vendor/sinatra/lib/sinatra.rb'
-
require 'app'
-
run Sinatra::Application
\ No newline at end of file
|
jstorimer/sinatra-shopify
|
668dcb890b0a0e4e7f7599cb2dcf2661ff1e26d1
|
Move some requires into config.ru.
|
diff --git a/app.rb b/app.rb
index d4358e8..2128da6 100644
--- a/app.rb
+++ b/app.rb
@@ -1,19 +1,18 @@
-require 'rubygems'
-require 'vendor/sinatra/lib/sinatra.rb'
require File.dirname(__FILE__) + '/lib/sinatra/shopify'
+set :raise_errors, true
get '/' do
redirect '/home'
end
get '/home' do
authorize!
@products = ShopifyAPI::Product.find(:all, :params => {:limit => 3})
@orders = ShopifyAPI::Order.find(:all, :params => {:limit => 3, :order => "created_at DESC" })
erb :index
end
get '/design' do
erb :design
end
\ No newline at end of file
diff --git a/config.ru b/config.ru
index b9f5e88..da5f78f 100644
--- a/config.ru
+++ b/config.ru
@@ -1,2 +1,6 @@
+require 'rubygems'
+require 'vendor/sinatra/lib/sinatra.rb'
+
require 'app'
+
run Sinatra::Application
\ No newline at end of file
|
jstorimer/sinatra-shopify
|
0968d2a223ba211e16f2957960c856a4e7b6d475
|
Remove ghost rack directory from vendor.
|
diff --git a/app.rb b/app.rb
index c57b01b..d4358e8 100644
--- a/app.rb
+++ b/app.rb
@@ -1,20 +1,19 @@
require 'rubygems'
-require 'vendor/rack/lib/rack.rb'
require 'vendor/sinatra/lib/sinatra.rb'
require File.dirname(__FILE__) + '/lib/sinatra/shopify'
get '/' do
redirect '/home'
end
get '/home' do
authorize!
@products = ShopifyAPI::Product.find(:all, :params => {:limit => 3})
@orders = ShopifyAPI::Order.find(:all, :params => {:limit => 3, :order => "created_at DESC" })
erb :index
end
get '/design' do
erb :design
end
\ No newline at end of file
diff --git a/vendor/rack b/vendor/rack
deleted file mode 160000
index fd1c1d2..0000000
--- a/vendor/rack
+++ /dev/null
@@ -1 +0,0 @@
-Subproject commit fd1c1d2e494d9a7d15e0458602ef121f244addc3
|
jstorimer/sinatra-shopify
|
c309f8755028c68c733aa390a65cc05916419fb3
|
Skeleton for shopify.yml
|
diff --git a/lib/sinatra/shopify.yml b/lib/sinatra/shopify.yml
new file mode 100644
index 0000000..be84358
--- /dev/null
+++ b/lib/sinatra/shopify.yml
@@ -0,0 +1,2 @@
+api_key: API_KEY
+secret: SECRET
\ No newline at end of file
|
jstorimer/sinatra-shopify
|
1c22266302b8455572afa02072cc096419e863e0
|
Vendored sinatra edge and rack edge.
|
diff --git a/app.rb b/app.rb
index 47a8399..c57b01b 100644
--- a/app.rb
+++ b/app.rb
@@ -1,19 +1,20 @@
require 'rubygems'
-require 'sinatra'
+require 'vendor/rack/lib/rack.rb'
+require 'vendor/sinatra/lib/sinatra.rb'
require File.dirname(__FILE__) + '/lib/sinatra/shopify'
get '/' do
redirect '/home'
end
get '/home' do
authorize!
@products = ShopifyAPI::Product.find(:all, :params => {:limit => 3})
@orders = ShopifyAPI::Order.find(:all, :params => {:limit => 3, :order => "created_at DESC" })
erb :index
end
get '/design' do
erb :design
end
\ No newline at end of file
diff --git a/vendor/rack b/vendor/rack
new file mode 160000
index 0000000..fd1c1d2
--- /dev/null
+++ b/vendor/rack
@@ -0,0 +1 @@
+Subproject commit fd1c1d2e494d9a7d15e0458602ef121f244addc3
diff --git a/vendor/sinatra/AUTHORS b/vendor/sinatra/AUTHORS
new file mode 100644
index 0000000..372390f
--- /dev/null
+++ b/vendor/sinatra/AUTHORS
@@ -0,0 +1,41 @@
+Sinatra was designed and developed by Blake Mizerany (bmizerany) in
+California. Continued development would not be possible without the ongoing
+financial support provided by [Heroku](http://heroku.com) and the emotional
+support provided by Adam Wiggins (adamwiggins) of Heroku, Chris Wanstrath (defunkt),
+PJ Hyett (pjhyett), and the rest of the GitHub crew.
+
+Special thanks to the following extraordinary individuals, who-out which
+Sinatra would not be possible:
+
+* Ryan Tomayko (rtomayko) for constantly fixing whitespace errors 60d5006
+* Ezra Zygmuntowicz (ezmobius) for initial help and letting Blake steal
+ some of merbs internal code.
+* Christopher Schneid (cschneid) for The Book, the blog (gittr.com),
+ irclogger.com, and a bunch of useful patches.
+* Markus Prinz (cypher) for patches over the years, caring about
+ the README, and hanging in there when times were rough.
+* Simon Rozet (sr) for a ton of doc patches, HAML options, and all that
+ advocacy stuff he's going to do for 1.0.
+* Erik Kastner (kastner) for fixing `MIME_TYPES` under Rack 0.5.
+* Ben Bleything (bleything) for caring about HTTP status codes and doc fixes.
+* Igal Koshevoy (igal) for root path detection under Thin/Passenger.
+* Jon Crosby (jcrosby) for coffee breaks, doc fixes, and just because, man.
+* Karel Minarik (karmi) for screaming until the website came back up.
+* Jeremy Evans (jeremyevans) for unbreaking optional path params (twice!)
+* The GitHub guys for stealing Blake's table.
+* Nickolas Means (nmeans) for Sass template support.
+* Victor Hugo Borja (vic) for splat'n routes specs and doco.
+* Avdi Grimm (avdi) for basic RSpec support.
+* Jack Danger Canty for a more accurate root directory and for making me
+ watch [this](http://www.youtube.com/watch?v=ueaHLHgskkw) just now.
+* Mathew Walker for making escaped paths work with static files.
+* Millions of Us for having the problem that led to Sinatra's conception.
+* Songbird for the problems that helped Sinatra's future become realized.
+* Rick Olson (technoweenie) for the killer plug at RailsConf '08.
+* Steven Garcia for the amazing custom artwork you see on 404's and 500's
+* Pat Nakajima (nakajima) for fixing non-nested params in nested params Hash's.
+
+and last but not least:
+
+* Frank Sinatra (chairman of the board) for having so much class he
+ deserves a web-framework named after him.
diff --git a/vendor/sinatra/CHANGES b/vendor/sinatra/CHANGES
new file mode 100644
index 0000000..ed06902
--- /dev/null
+++ b/vendor/sinatra/CHANGES
@@ -0,0 +1,377 @@
+= 1.0 / unreleased
+
+ * Route handlers, before filters, templates, error mappings, and
+ middleware are now resolved dynamically up the inheritance hierarchy
+ when needed instead of duplicating the superclass's version when
+ a new Sinatra::Base subclass is created. This should fix a variety
+ of issues with extensions that need to add any of these things
+ to the base class.
+
+= 0.9.2 / 2009-05-18
+
+ * This version is compatible with Rack 1.0. [Rein Henrichs]
+
+ * The development-mode unhandled exception / error page has been
+ greatly enhanced, functionally and aesthetically. The error
+ page is used when the :show_exceptions option is enabled and an
+ exception propagates outside of a route handler or before filter.
+ [Simon Rozet / Matte Noble / Ryan Tomayko]
+
+ * Backtraces that move through templates now include filenames and
+ line numbers where possible. [#51 / S. Brent Faulkner]
+
+ * All templates now have an app-level option for setting default
+ template options (:haml, :sass, :erb, :builder). The app-level
+ option value must be a Hash if set and is merged with the
+ template options specified to the render method (Base#haml,
+ Base#erb, Base#builder). [S. Brent Faulkner, Ryan Tomayko]
+
+ * The method signature for all template rendering methods has
+ been unified: "def engine(template, options={}, locals={})".
+ The options Hash now takes the generic :views, :layout, and
+ :locals options but also any template-specific options. The
+ generic options are removed before calling the template specific
+ render method. Locals may be specified using either the
+ :locals key in the options hash or a second Hash option to the
+ rendering method. [#191 / Ryan Tomayko]
+
+ * The receiver is now passed to "configure" blocks. This
+ allows for the following idiom in top-level apps:
+ configure { |app| set :foo, app.root + '/foo' }
+ [TJ Holowaychuck / Ryan Tomayko]
+
+ * The "sinatra/test" lib is deprecated and will be removed in
+ Sinatra 1.0. This includes the Sinatra::Test module and
+ Sinatra::TestHarness class in addition to all the framework
+ test helpers that were deprecated in 0.9.1. The Rack::Test
+ lib should be used instead: http://gitrdoc.com/brynary/rack-test
+ [#176 / Simon Rozet]
+
+ * Development mode source file reloading has been removed. The
+ "shotgun" (http://rtomayko.github.com/shotgun/) program can be
+ used to achieve the same basic functionality in most situations.
+ Passenger users should use the "tmp/always_restart.txt"
+ file (http://tinyurl.com/c67o4h). [#166 / Ryan Tomayko]
+
+ * Auto-requiring template libs in the erb, builder, haml, and
+ sass methods is deprecated due to thread-safety issues. You must
+ require the template libs explicitly in your app file. [Simon Rozet]
+
+ * A new Sinatra::Base#route_missing method was added. route_missing
+ is sent when no route matches the request or all route handlers
+ pass. The default implementation forwards the request to the
+ downstream app when running as middleware (i.e., "@app" is
+ non-nil), or raises a NotFound exception when no downstream app
+ is defined. Subclasses can override this method to perform custom
+ route miss logic. [Jon Crosby]
+
+ * A new Sinatra::Base#route_eval method was added. The method
+ yields to the block and throws :halt with the result. Subclasses
+ can override this method to tap into the route execution logic.
+ [TJ Holowaychuck]
+
+ * Fix the "-x" (enable request mutex / locking) command line
+ argument. Passing -x now properly sets the :lock option.
+ [S. Brent Faulkner, Ryan Tomayko]
+
+ * Fix writer ("foo=") and predicate ("foo?") methods in extension
+ modules not being added to the registering class.
+ [#172 / Pat Nakajima]
+
+ * Fix in-file templates when running alongside activesupport and
+ fatal errors when requiring activesupport before sinatra
+ [#178 / Brian Candler]
+
+ * Fix various issues running on Google AppEngine.
+ [Samuel Goebert, Simon Rozet]
+
+ * Fix in-file templates __END__ detection when __END__ exists with
+ other stuff on a line [Yoji Shidara]
+
+= 0.9.1.1 / 2009-03-09
+
+ * Fix directory traversal vulnerability in default static files
+ route. See [#177] for more info.
+
+= 0.9.1 / 2009-03-01
+
+ * Sinatra now runs under Ruby 1.9.1 [#61]
+
+ * Route patterns (splats, :named, or Regexp captures) are now
+ passed as arguments to the block. [#140]
+
+ * The "helpers" method now takes a variable number of modules
+ along with the normal block syntax. [#133]
+
+ * New request-level #forward method for middleware components: passes
+ the env to the downstream app and merges the response status, headers,
+ and body into the current context. [#126]
+
+ * Requests are now automatically forwarded to the downstream app when
+ running as middleware and no matching route is found or all routes
+ pass.
+
+ * New simple API for extensions/plugins to add DSL-level and
+ request-level methods. Use Sinatra.register(mixin) to extend
+ the DSL with all public methods defined in the mixin module;
+ use Sinatra.helpers(mixin) to make all public methods defined
+ in the mixin module available at the request level. [#138]
+ See http://www.sinatrarb.com/extensions.html for details.
+
+ * Named parameters in routes now capture the "." character. This makes
+ routes like "/:path/:filename" match against requests like
+ "/foo/bar.txt"; in this case, "params[:filename]" is "bar.txt".
+ Previously, the route would not match at all.
+
+ * Added request-level "redirect back" to redirect to the referring
+ URL.
+
+ * Added a new "clean_trace" option that causes backtraces dumped
+ to rack.errors and displayed on the development error page to
+ omit framework and core library backtrace lines. The option is
+ enabled by default. [#77]
+
+ * The ERB output buffer is now available to helpers via the @_out_buf
+ instance variable.
+
+ * It's now much easier to test sessions in unit tests by passing a
+ ":session" option to any of the mock request methods. e.g.,
+ get '/', {}, :session => { 'foo' => 'bar' }
+
+ * The testing framework specific files ('sinatra/test/spec',
+ 'sinatra/test/bacon', 'sinatra/test/rspec', etc.) have been deprecated.
+ See http://sinatrarb.com/testing.html for instructions on setting up
+ a testing environment with these frameworks.
+
+ * The request-level #send_data method from Sinatra 0.3.3 has been added
+ for compatibility but is deprecated.
+
+ * Fix :provides causing crash on any request when request has no
+ Accept header [#139]
+
+ * Fix that ERB templates were evaluated twice per "erb" call.
+
+ * Fix app-level middleware not being run when the Sinatra application is
+ run as middleware.
+
+ * Fixed some issues with running under Rack's CGI handler caused by
+ writing informational stuff to stdout.
+
+ * Fixed that reloading was sometimes enabled when starting from a
+ rackup file [#110]
+
+ * Fixed that "." in route patterns erroneously matched any character
+ instead of a literal ".". [#124]
+
+= 0.9.0.4 / 2009-01-25
+
+ * Using halt with more than 1 args causes ArgumentError [#131]
+ * using halt in a before filter doesn't modify response [#127]
+ * Add deprecated Sinatra::EventContext to unbreak plugins [#130]
+ * Give access to GET/POST params in filters [#129]
+ * Preserve non-nested params in nested params hash [#117]
+ * Fix backtrace dump with Rack::Lint [#116]
+
+= 0.9.0.3 / 2009-01-21
+
+ * Fall back on mongrel then webrick when thin not found. [#75]
+ * Use :environment instead of :env in test helpers to
+ fix deprecation warnings coming from framework.
+ * Make sinatra/test/rspec work again [#113]
+ * Fix app_file detection on windows [#118]
+ * Fix static files with Rack::Lint in pipeline [#121]
+
+= 0.9.0.2 / 2009-01-18
+
+ * Halting a before block should stop processing of routes [#85]
+ * Fix redirect/halt in before filters [#85]
+
+= 0.9.0 / 2009-01-18
+
+ * Works with and requires Rack >= 0.9.1
+
+ * Multiple Sinatra applications can now co-exist peacefully within a
+ single process. The new "Sinatra::Base" class can be subclassed to
+ establish a blank-slate Rack application or middleware component.
+ Documentation on using these features is forth-coming; the following
+ provides the basic gist: http://gist.github.com/38605
+
+ * Parameters with subscripts are now parsed into a nested/recursive
+ Hash structure. e.g., "post[title]=Hello&post[body]=World" yields
+ params: {'post' => {'title' => 'Hello', 'body' => 'World'}}.
+
+ * Regular expressions may now be used in route pattens; captures are
+ available at "params[:captures]".
+
+ * New ":provides" route condition takes an array of mime types and
+ matches only when an Accept request header is present with a
+ corresponding type. [cypher]
+
+ * New request-level "pass" method; immediately exits the current block
+ and passes control to the next matching route.
+
+ * The request-level "body" method now takes a block; evaluation is
+ deferred until an attempt is made to read the body. The block must
+ return a String or Array.
+
+ * New "route conditions" system for attaching rules for when a route
+ matches. The :agent and :host route options now use this system.
+
+ * New "dump_errors" option controls whether the backtrace is dumped to
+ rack.errors when an exception is raised from a route. The option is
+ enabled by default for top-level apps.
+
+ * Better default "app_file", "root", "public", and "views" location
+ detection; changes to "root" and "app_file" automatically cascade to
+ other options that depend on them.
+
+ * Error mappings are now split into two distinct layers: exception
+ mappings and custom error pages. Exception mappings are registered
+ with "error(Exception)" and are run only when the app raises an
+ exception. Custom error pages are registered with "error(status_code)",
+ where "status_code" is an integer, and are run any time the response
+ has the status code specified. It's also possible to register an error
+ page for a range of status codes: "error(500..599)".
+
+ * In-file templates are now automatically imported from the file that
+ requires 'sinatra'. The use_in_file_templates! method is still available
+ for loading templates from other files.
+
+ * Sinatra's testing support is no longer dependent on Test::Unit. Requiring
+ 'sinatra/test' adds the Sinatra::Test module and Sinatra::TestHarness
+ class, which can be used with any test framework. The 'sinatra/test/unit',
+ 'sinatra/test/spec', 'sinatra/test/rspec', or 'sinatra/test/bacon' files
+ can be required to setup a framework-specific testing environment. See the
+ README for more information.
+
+ * Added support for Bacon (test framework). The 'sinatra/test/bacon' file
+ can be required to setup Sinatra test helpers on Bacon::Context.
+
+ * Deprecated "set_option" and "set_options"; use "set" instead.
+
+ * Deprecated the "env" option ("options.env"); use "environment" instead.
+
+ * Deprecated the request level "stop" method; use "halt" instead.
+
+ * Deprecated the request level "entity_tag" method; use "etag" instead.
+ Both "entity_tag" and "etag" were previously supported.
+
+ * Deprecated the request level "headers" method (HTTP response headers);
+ use "response['Header-Name']" instead.
+
+ * Deprecated "Sinatra.application"; use "Sinatra::Application" instead.
+
+ * Deprecated setting Sinatra.application = nil to reset an application.
+ This should no longer be necessary.
+
+ * Deprecated "Sinatra.default_options"; use
+ "Sinatra::Default.set(key, value)" instead.
+
+ * Deprecated the "ServerError" exception. All Exceptions are now
+ treated as internal server errors and result in a 500 response
+ status.
+
+ * Deprecated the "get_it", "post_it", "put_it", "delete_it", and "head_it"
+ test helper methods. Use "get", "post", "put", "delete", and "head",
+ respectively, instead.
+
+ * Removed Event and EventContext classes. Applications are defined in a
+ subclass of Sinatra::Base; each request is processed within an
+ instance.
+
+= 0.3.3 / 2009-01-06
+
+ * Pin to Rack 0.4.0 (this is the last release on Rack 0.4)
+
+ * Log unhandled exception backtraces to rack.errors.
+
+ * Use RACK_ENV environment variable to establish Sinatra
+ environment when given. Thin sets this when started with
+ the -e argument.
+
+ * BUG: raising Sinatra::NotFound resulted in a 500 response
+ code instead of 404.
+
+ * BUG: use_in_file_templates! fails with CR/LF (#45)
+
+ * BUG: Sinatra detects the app file and root path when run under
+ thin/passenger.
+
+= 0.3.2
+
+ * BUG: Static and send_file read entire file into String before
+ sending. Updated to stream with 8K chunks instead.
+
+ * Rake tasks and assets for building basic documentation website.
+ See http://sinatra.rubyforge.org
+
+ * Various minor doc fixes.
+
+= 0.3.1
+
+ * Unbreak optional path parameters [jeremyevans]
+
+= 0.3.0
+
+ * Add sinatra.gemspec w/ support for github gem builds. Forks can now
+ enable the build gem option in github to get free username-sinatra.gem
+ builds: gem install username-sinatra.gem --source=http://gems.github.com/
+
+ * Require rack-0.4 gem; removes frozen rack dir.
+
+ * Basic RSpec support; require 'sinatra/test/rspec' instead of
+ 'sinatra/test/spec' to use. [avdi]
+
+ * before filters can modify request environment vars used for
+ routing (e.g., PATH_INFO, REQUEST_METHOD, etc.) for URL rewriting
+ type functionality.
+
+ * In-file templates now uses @@ instead of ## as template separator.
+
+ * Top-level environment test predicates: development?, test?, production?
+
+ * Top-level "set", "enable", and "disable" methods for tweaking
+ app options. [rtomayko]
+
+ * Top-level "use" method for building Rack middleware pipelines
+ leading to app. See README for usage. [rtomayko]
+
+ * New "reload" option - set false to disable reloading in development.
+
+ * New "host" option - host/ip to bind to [cschneid]
+
+ * New "app_file" option - override the file to reload in development
+ mode [cschneid]
+
+ * Development error/not_found page cleanup [sr, adamwiggins]
+
+ * Remove a bunch of core extensions (String#to_param, String#from_param,
+ Hash#from_params, Hash#to_params, Hash#symbolize_keys, Hash#pass)
+
+ * Various grammar and formatting fixes to README; additions on
+ community and contributing [cypher]
+
+ * Build RDoc using Hanna template: http://sinatrarb.rubyforge.org/api
+
+ * Specs, documentation and fixes for splat'n routes [vic]
+
+ * Fix whitespace errors across all source files. [rtomayko]
+
+ * Fix streaming issues with Mongrel (body not closed). [bmizerany]
+
+ * Fix various issues with environment not being set properly (configure
+ blocks not running, error pages not registering, etc.) [cypher]
+
+ * Fix to allow locals to be passed to ERB templates [cschneid]
+
+ * Fix locking issues causing random errors during reload in development.
+
+ * Fix for escaped paths not resolving static files [Matthew Walker]
+
+= 0.2.1
+
+ * File upload fix and minor tweaks.
+
+= 0.2.0
+
+ * Initial gem release of 0.2 codebase.
diff --git a/vendor/sinatra/LICENSE b/vendor/sinatra/LICENSE
new file mode 100644
index 0000000..145fdff
--- /dev/null
+++ b/vendor/sinatra/LICENSE
@@ -0,0 +1,22 @@
+Copyright (c) 2007, 2008, 2009 Blake Mizerany
+
+Permission is hereby granted, free of charge, to any person
+obtaining a copy of this software and associated documentation
+files (the "Software"), to deal in the Software without
+restriction, including without limitation the rights to use,
+copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the
+Software is furnished to do so, subject to the following
+conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
+OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+OTHER DEALINGS IN THE SOFTWARE.
\ No newline at end of file
diff --git a/vendor/sinatra/README.rdoc b/vendor/sinatra/README.rdoc
new file mode 100644
index 0000000..11f0d8b
--- /dev/null
+++ b/vendor/sinatra/README.rdoc
@@ -0,0 +1,573 @@
+= Sinatra
+
+Sinatra is a DSL for quickly creating web-applications in Ruby with minimal
+effort:
+
+ # myapp.rb
+ require 'rubygems'
+ require 'sinatra'
+ get '/' do
+ 'Hello world!'
+ end
+
+Install the gem and run with:
+
+ sudo gem install sinatra
+ ruby myapp.rb
+
+View at: http://localhost:4567
+
+== Routes
+
+In Sinatra, a route is an HTTP method paired with an URL matching pattern.
+Each route is associated with a block:
+
+ get '/' do
+ .. show something ..
+ end
+
+ post '/' do
+ .. create something ..
+ end
+
+ put '/' do
+ .. update something ..
+ end
+
+ delete '/' do
+ .. annihilate something ..
+ end
+
+Routes are matched in the order they are defined. The first route that
+matches the request is invoked.
+
+Route patterns may include named parameters, accessible via the
+<tt>params</tt> hash:
+
+ get '/hello/:name' do
+ # matches "GET /hello/foo" and "GET /hello/bar"
+ # params[:name] is 'foo' or 'bar'
+ "Hello #{params[:name]}!"
+ end
+
+You can also access named parameters via block parameters:
+
+ get '/hello/:name' do |n|
+ "Hello #{n}!"
+ end
+
+Route patterns may also include splat (or wildcard) parameters, accessible
+via the <tt>params[:splat]</tt> array.
+
+ get '/say/*/to/*' do
+ # matches /say/hello/to/world
+ params[:splat] # => ["hello", "world"]
+ end
+
+ get '/download/*.*' do
+ # matches /download/path/to/file.xml
+ params[:splat] # => ["path/to/file", "xml"]
+ end
+
+Route matching with Regular Expressions:
+
+ get %r{/hello/([\w]+)} do
+ "Hello, #{params[:captures].first}!"
+ end
+
+Or with a block parameter:
+
+ get %r{/hello/([\w]+)} do |c|
+ "Hello, #{c}!"
+ end
+
+Routes may include a variety of matching conditions, such as the user agent:
+
+ get '/foo', :agent => /Songbird (\d\.\d)[\d\/]*?/ do
+ "You're using Songbird version #{params[:agent][0]}"
+ end
+
+ get '/foo' do
+ # Matches non-songbird browsers
+ end
+
+== Static Files
+
+Static files are served from the <tt>./public</tt> directory. You can specify
+a different location by setting the <tt>:public</tt> option:
+
+ set :public, File.dirname(__FILE__) + '/static'
+
+Note that the public directory name is not included in the URL. A file
+<tt>./public/css/style.css</tt> is made available as
+<tt>http://example.com/css/style.css</tt>.
+
+== Views / Templates
+
+Templates are assumed to be located directly under the <tt>./views</tt>
+directory. To use a different views directory:
+
+ set :views, File.dirname(__FILE__) + '/templates'
+
+One important thing to remember is that you always have to reference
+templates with symbols, even if they're in a subdirectory (in this
+case use <tt>:'subdir/template'</tt>). Rendering methods will render
+any strings passed to them directly.
+
+=== Haml Templates
+
+The haml gem/library is required to render HAML templates:
+
+ ## You'll need to require haml in your app
+ require 'haml'
+
+ get '/' do
+ haml :index
+ end
+
+Renders <tt>./views/index.haml</tt>.
+
+{Haml's options}[http://haml.hamptoncatlin.com/docs/rdoc/classes/Haml.html]
+can be set globally through Sinatra's configurations,
+see {Options and Configurations}[http://www.sinatrarb.com/configuration.html],
+and overridden on an individual basis.
+
+ set :haml, {:format => :html5 } # default Haml format is :xhtml
+
+ get '/' do
+ haml :index, :haml_options => {:format => :html4 } # overridden
+ end
+
+
+=== Erb Templates
+
+ ## You'll need to require erb in your app
+ require 'erb'
+
+ get '/' do
+ erb :index
+ end
+
+Renders <tt>./views/index.erb</tt>
+
+=== Builder Templates
+
+The builder gem/library is required to render builder templates:
+
+ ## You'll need to require builder in your app
+ require 'builder'
+
+ get '/' do
+ content_type 'application/xml', :charset => 'utf-8'
+ builder :index
+ end
+
+Renders <tt>./views/index.builder</tt>.
+
+=== Sass Templates
+
+The sass gem/library is required to render Sass templates:
+
+ ## You'll need to require haml or sass in your app
+ require 'sass'
+
+ get '/stylesheet.css' do
+ content_type 'text/css', :charset => 'utf-8'
+ sass :stylesheet
+ end
+
+Renders <tt>./views/stylesheet.sass</tt>.
+
+{Sass' options}[http://haml.hamptoncatlin.com/docs/rdoc/classes/Sass.html]
+can be set globally through Sinatra's configurations,
+see {Options and Configurations}[http://www.sinatrarb.com/configuration.html],
+and overridden on an individual basis.
+
+ set :sass, {:style => :compact } # default Sass style is :nested
+
+ get '/stylesheet.css' do
+ content_type 'text/css', :charset => 'utf-8'
+ sass :stylesheet, :sass_options => {:style => :expanded } # overridden
+ end
+
+
+=== Inline Templates
+
+ get '/' do
+ haml '%div.title Hello World'
+ end
+
+Renders the inlined template string.
+
+=== Accessing Variables in Templates
+
+Templates are evaluated within the same context as route handlers. Instance
+variables set in route handlers are direcly accessible by templates:
+
+ get '/:id' do
+ @foo = Foo.find(params[:id])
+ haml '%h1= @foo.name'
+ end
+
+Or, specify an explicit Hash of local variables:
+
+ get '/:id' do
+ foo = Foo.find(params[:id])
+ haml '%h1= foo.name', :locals => { :foo => foo }
+ end
+
+This is typically used when rendering templates as partials from within
+other templates.
+
+=== In-file Templates
+
+Templates may be defined at the end of the source file:
+
+ require 'rubygems'
+ require 'sinatra'
+
+ get '/' do
+ haml :index
+ end
+
+ __END__
+
+ @@ layout
+ %html
+ = yield
+
+ @@ index
+ %div.title Hello world!!!!!
+
+NOTE: In-file templates defined in the source file that requires sinatra
+are automatically loaded. Call the <tt>use_in_file_templates!</tt>
+method explicitly if you have in-file templates in other source files.
+
+=== Named Templates
+
+Templates may also be defined using the top-level <tt>template</tt> method:
+
+ template :layout do
+ "%html\n =yield\n"
+ end
+
+ template :index do
+ '%div.title Hello World!'
+ end
+
+ get '/' do
+ haml :index
+ end
+
+If a template named "layout" exists, it will be used each time a template
+is rendered. You can disable layouts by passing <tt>:layout => false</tt>.
+
+ get '/' do
+ haml :index, :layout => !request.xhr?
+ end
+
+== Helpers
+
+Use the top-level <tt>helpers</tt> method to define helper methods for use in
+route handlers and templates:
+
+ helpers do
+ def bar(name)
+ "#{name}bar"
+ end
+ end
+
+ get '/:name' do
+ bar(params[:name])
+ end
+
+== Filters
+
+Before filters are evaluated before each request within the context of the
+request and can modify the request and response. Instance variables set in
+filters are accessible by routes and templates:
+
+ before do
+ @note = 'Hi!'
+ request.path_info = '/foo/bar/baz'
+ end
+
+ get '/foo/*' do
+ @note #=> 'Hi!'
+ params[:splat] #=> 'bar/baz'
+ end
+
+== Halting
+
+To immediately stop a request during a before filter or route use:
+
+ halt
+
+You can also specify a body when halting ...
+
+ halt 'this will be the body'
+
+Or set the status and body ...
+
+ halt 401, 'go away!'
+
+== Passing
+
+A route can punt processing to the next matching route using <tt>pass</tt>:
+
+ get '/guess/:who' do
+ pass unless params[:who] == 'Frank'
+ "You got me!"
+ end
+
+ get '/guess/*' do
+ "You missed!"
+ end
+
+The route block is immediately exited and control continues with the next
+matching route. If no matching route is found, a 404 is returned.
+
+== Configuration
+
+Run once, at startup, in any environment:
+
+ configure do
+ ...
+ end
+
+Run only when the environment (RACK_ENV environment variable) is set to
+<tt>:production</tt>:
+
+ configure :production do
+ ...
+ end
+
+Run when the environment is set to either <tt>:production</tt> or
+<tt>:test</tt>:
+
+ configure :production, :test do
+ ...
+ end
+
+== Error handling
+
+Error handlers run within the same context as routes and before filters, which
+means you get all the goodies it has to offer, like <tt>haml</tt>, <tt>erb</tt>,
+<tt>halt</tt>, etc.
+
+=== Not Found
+
+When a <tt>Sinatra::NotFound</tt> exception is raised, or the response's status
+code is 404, the <tt>not_found</tt> handler is invoked:
+
+ not_found do
+ 'This is nowhere to be found'
+ end
+
+=== Error
+
+The +error+ handler is invoked any time an exception is raised from a route
+block or before filter. The exception object can be obtained from the
+<tt>sinatra.error</tt> Rack variable:
+
+ error do
+ 'Sorry there was a nasty error - ' + env['sinatra.error'].name
+ end
+
+Custom errors:
+
+ error MyCustomError do
+ 'So what happened was...' + request.env['sinatra.error'].message
+ end
+
+Then, if this happens:
+
+ get '/' do
+ raise MyCustomError, 'something bad'
+ end
+
+You get this:
+
+ So what happened was... something bad
+
+Sinatra installs special <tt>not_found</tt> and <tt>error</tt> handlers when
+running under the development environment.
+
+== Mime types
+
+When using <tt>send_file</tt> or static files you may have mime types Sinatra
+doesn't understand. Use +mime+ to register them by file extension:
+
+ mime :foo, 'text/foo'
+
+== Rack Middleware
+
+Sinatra rides on Rack[http://rack.rubyforge.org/], a minimal standard
+interface for Ruby web frameworks. One of Rack's most interesting capabilities
+for application developers is support for "middleware" -- components that sit
+between the server and your application monitoring and/or manipulating the
+HTTP request/response to provide various types of common functionality.
+
+Sinatra makes building Rack middleware pipelines a cinch via a top-level
++use+ method:
+
+ require 'sinatra'
+ require 'my_custom_middleware'
+
+ use Rack::Lint
+ use MyCustomMiddleware
+
+ get '/hello' do
+ 'Hello World'
+ end
+
+The semantics of +use+ are identical to those defined for the
+Rack::Builder[http://rack.rubyforge.org/doc/classes/Rack/Builder.html] DSL
+(most frequently used from rackup files). For example, the +use+ method
+accepts multiple/variable args as well as blocks:
+
+ use Rack::Auth::Basic do |username, password|
+ username == 'admin' && password == 'secret'
+ end
+
+Rack is distributed with a variety of standard middleware for logging,
+debugging, URL routing, authentication, and session handling. Sinatra uses
+many of of these components automatically based on configuration so you
+typically don't have to +use+ them explicitly.
+
+== Testing
+
+Sinatra tests can be written using any Rack-based testing library
+or framework. {Rack::Test}[http://gitrdoc.com/brynary/rack-test] is
+recommended:
+
+ require 'my_sinatra_app'
+ require 'rack/test'
+
+ class MyAppTest < Test::Unit::TestCase
+ include Rack::Test::Methods
+
+ def app
+ Sinatra::Application
+ end
+
+ def test_my_default
+ get '/'
+ assert_equal 'Hello World!', last_response.body
+ end
+
+ def test_with_params
+ get '/meet', :name => 'Frank'
+ assert_equal 'Hello Frank!', last_response.body
+ end
+
+ def test_with_rack_env
+ get '/', {}, 'HTTP_USER_AGENT' => 'Songbird'
+ assert_equal "You're using Songbird!", last_response.body
+ end
+ end
+
+NOTE: The built-in Sinatra::Test module and Sinatra::TestHarness class
+are deprecated as of the 0.9.2 release.
+
+== Sinatra::Base - Middleware, Libraries, and Modular Apps
+
+Defining your app at the top-level works well for micro-apps but has
+considerable drawbacks when building reuseable components such as Rack
+middleware, Rails metal, simple libraries with a server component, or
+even Sinatra extensions. The top-level DSL pollutes the Object namespace
+and assumes a micro-app style configuration (e.g., a single application
+file, ./public and ./views directories, logging, exception detail page,
+etc.). That's where Sinatra::Base comes into play:
+
+ require 'sinatra/base'
+
+ class MyApp < Sinatra::Base
+ set :sessions, true
+ set :foo, 'bar'
+
+ get '/' do
+ 'Hello world!'
+ end
+ end
+
+The MyApp class is an independent Rack component that can act as
+Rack middleware, a Rack application, or Rails metal. You can +use+ or
++run+ this class from a rackup +config.ru+ file; or, control a server
+component shipped as a library:
+
+ MyApp.run! :host => 'localhost', :port => 9090
+
+The methods available to Sinatra::Base subclasses are exactly as those
+available via the top-level DSL. Most top-level apps can be converted to
+Sinatra::Base components with two modifications:
+
+* Your file should require +sinatra/base+ instead of +sinatra+;
+ otherwise, all of Sinatra's DSL methods are imported into the main
+ namespace.
+* Put your app's routes, error handlers, filters, and options in a subclass
+ of Sinatra::Base.
+
++Sinatra::Base+ is a blank slate. Most options are disabled by default,
+including the built-in server. See {Options and Configuration}[http://sinatra.github.com/configuration.html]
+for details on available options and their behavior.
+
+SIDEBAR: Sinatra's top-level DSL is implemented using a simple delegation
+system. The +Sinatra::Application+ class -- a special subclass of
+Sinatra::Base -- receives all :get, :put, :post, :delete, :before,
+:error, :not_found, :configure, and :set messages sent to the
+top-level. Have a look at the code for yourself: here's the
+{Sinatra::Delegator mixin}[http://github.com/sinatra/sinatra/blob/master/lib/sinatra/base.rb#L1064]
+being {included into the main namespace}[http://github.com/sinatra/sinatra/blob/master/lib/sinatra/main.rb#L25].
+
+== Command line
+
+Sinatra applications can be run directly:
+
+ ruby myapp.rb [-h] [-x] [-e ENVIRONMENT] [-p PORT] [-s HANDLER]
+
+Options are:
+
+ -h # help
+ -p # set the port (default is 4567)
+ -e # set the environment (default is development)
+ -s # specify rack server/handler (default is thin)
+ -x # turn on the mutex lock (default is off)
+
+== The Bleeding Edge
+
+If you would like to use Sinatra's latest bleeding code, create a local
+clone and run your app with the <tt>sinatra/lib</tt> directory on the
+<tt>LOAD_PATH</tt>:
+
+ cd myapp
+ git clone git://github.com/sinatra/sinatra.git
+ ruby -Isinatra/lib myapp.rb
+
+Alternatively, you can add the <tt>sinatra/lib</tt> directory to the
+<tt>LOAD_PATH</tt> in your application:
+
+ $LOAD_PATH.unshift File.dirname(__FILE__) + '/sinatra/lib'
+ require 'rubygems'
+ require 'sinatra'
+
+ get '/about' do
+ "I'm running version " + Sinatra::VERSION
+ end
+
+To update the Sinatra sources in the future:
+
+ cd myproject/sinatra
+ git pull
+
+== More
+
+* {Project Website}[http://sinatra.github.com/] - Additional documentation,
+ news, and links to other resources.
+* {Contributing}[http://sinatra.github.com/contributing.html] - Find a bug? Need
+ help? Have a patch?
+* {Lighthouse}[http://sinatra.lighthouseapp.com] - Issue tracking and release
+ planning.
+* {Twitter}[http://twitter.com/sinatra]
+* {Mailing List}[http://groups.google.com/group/sinatrarb]
+* {IRC: #sinatra}[irc://chat.freenode.net/#sinatra] on http://freenode.net
diff --git a/vendor/sinatra/Rakefile b/vendor/sinatra/Rakefile
new file mode 100644
index 0000000..3421710
--- /dev/null
+++ b/vendor/sinatra/Rakefile
@@ -0,0 +1,119 @@
+require 'rake/clean'
+require 'rake/testtask'
+require 'fileutils'
+
+task :default => :test
+task :spec => :test
+
+# SPECS ===============================================================
+
+Rake::TestTask.new(:test) do |t|
+ t.test_files = FileList['test/*_test.rb']
+ t.ruby_opts = ['-rubygems'] if defined? Gem
+end
+
+# PACKAGING ============================================================
+
+# Load the gemspec using the same limitations as github
+def spec
+ @spec ||=
+ begin
+ require 'rubygems/specification'
+ data = File.read('sinatra.gemspec')
+ spec = nil
+ Thread.new { spec = eval("$SAFE = 3\n#{data}") }.join
+ spec
+ end
+end
+
+def package(ext='')
+ "pkg/sinatra-#{spec.version}" + ext
+end
+
+desc 'Build packages'
+task :package => %w[.gem .tar.gz].map {|e| package(e)}
+
+desc 'Build and install as local gem'
+task :install => package('.gem') do
+ sh "gem install #{package('.gem')}"
+end
+
+directory 'pkg/'
+CLOBBER.include('pkg')
+
+file package('.gem') => %w[pkg/ sinatra.gemspec] + spec.files do |f|
+ sh "gem build sinatra.gemspec"
+ mv File.basename(f.name), f.name
+end
+
+file package('.tar.gz') => %w[pkg/] + spec.files do |f|
+ sh <<-SH
+ git archive \
+ --prefix=sinatra-#{source_version}/ \
+ --format=tar \
+ HEAD | gzip > #{f.name}
+ SH
+end
+
+# Rubyforge Release / Publish Tasks ==================================
+
+desc 'Publish gem and tarball to rubyforge'
+task 'release' => [package('.gem'), package('.tar.gz')] do |t|
+ sh <<-end
+ rubyforge add_release sinatra sinatra #{spec.version} #{package('.gem')} &&
+ rubyforge add_file sinatra sinatra #{spec.version} #{package('.tar.gz')}
+ end
+end
+
+# Website ============================================================
+# Building docs requires HAML and the hanna gem:
+# gem install mislav-hanna --source=http://gems.github.com
+
+task 'doc' => ['doc:api']
+
+desc 'Generate Hanna RDoc under doc/api'
+task 'doc:api' => ['doc/api/index.html']
+
+file 'doc/api/index.html' => FileList['lib/**/*.rb','README.rdoc'] do |f|
+ rb_files = f.prerequisites
+ sh((<<-end).gsub(/\s+/, ' '))
+ hanna --charset utf8 \
+ --fmt html \
+ --inline-source \
+ --line-numbers \
+ --main README.rdoc \
+ --op doc/api \
+ --title 'Sinatra API Documentation' \
+ #{rb_files.join(' ')}
+ end
+end
+CLEAN.include 'doc/api'
+
+# Gemspec Helpers ====================================================
+
+def source_version
+ line = File.read('lib/sinatra/base.rb')[/^\s*VERSION = .*/]
+ line.match(/.*VERSION = '(.*)'/)[1]
+end
+
+task 'sinatra.gemspec' => FileList['{lib,test,compat}/**','Rakefile','CHANGES','*.rdoc'] do |f|
+ # read spec file and split out manifest section
+ spec = File.read(f.name)
+ head, manifest, tail = spec.split(" # = MANIFEST =\n")
+ # replace version and date
+ head.sub!(/\.version = '.*'/, ".version = '#{source_version}'")
+ head.sub!(/\.date = '.*'/, ".date = '#{Date.today.to_s}'")
+ # determine file list from git ls-files
+ files = `git ls-files`.
+ split("\n").
+ sort.
+ reject{ |file| file =~ /^\./ }.
+ reject { |file| file =~ /^doc/ }.
+ map{ |file| " #{file}" }.
+ join("\n")
+ # piece file back together and write...
+ manifest = " s.files = %w[\n#{files}\n ]\n"
+ spec = [head,manifest,tail].join(" # = MANIFEST =\n")
+ File.open(f.name, 'w') { |io| io.write(spec) }
+ puts "updated #{f.name}"
+end
diff --git a/vendor/sinatra/lib/sinatra.rb b/vendor/sinatra/lib/sinatra.rb
new file mode 100644
index 0000000..ce3ad6a
--- /dev/null
+++ b/vendor/sinatra/lib/sinatra.rb
@@ -0,0 +1,7 @@
+libdir = File.dirname(__FILE__)
+$LOAD_PATH.unshift(libdir) unless $LOAD_PATH.include?(libdir)
+
+require 'sinatra/base'
+require 'sinatra/main'
+
+use_in_file_templates!
diff --git a/vendor/sinatra/lib/sinatra/base.rb b/vendor/sinatra/lib/sinatra/base.rb
new file mode 100644
index 0000000..e153b38
--- /dev/null
+++ b/vendor/sinatra/lib/sinatra/base.rb
@@ -0,0 +1,1099 @@
+require 'thread'
+require 'time'
+require 'uri'
+require 'rack'
+require 'rack/builder'
+require 'sinatra/showexceptions'
+
+module Sinatra
+ VERSION = '0.10.1'
+
+ # The request object. See Rack::Request for more info:
+ # http://rack.rubyforge.org/doc/classes/Rack/Request.html
+ class Request < Rack::Request
+ def user_agent
+ @env['HTTP_USER_AGENT']
+ end
+
+ # Returns an array of acceptable media types for the response
+ def accept
+ @env['HTTP_ACCEPT'].to_s.split(',').map { |a| a.strip }
+ end
+
+ # Override Rack 0.9.x's #params implementation (see #72 in lighthouse)
+ def params
+ self.GET.update(self.POST)
+ rescue EOFError => boom
+ self.GET
+ end
+ end
+
+ # The response object. See Rack::Response and Rack::ResponseHelpers for
+ # more info:
+ # http://rack.rubyforge.org/doc/classes/Rack/Response.html
+ # http://rack.rubyforge.org/doc/classes/Rack/Response/Helpers.html
+ class Response < Rack::Response
+ def finish
+ @body = block if block_given?
+ if [204, 304].include?(status.to_i)
+ header.delete "Content-Type"
+ [status.to_i, header.to_hash, []]
+ else
+ body = @body || []
+ body = [body] if body.respond_to? :to_str
+ if body.respond_to?(:to_ary)
+ header["Content-Length"] = body.to_ary.
+ inject(0) { |len, part| len + Rack::Utils.bytesize(part) }.to_s
+ end
+ [status.to_i, header.to_hash, body]
+ end
+ end
+ end
+
+ class NotFound < NameError #:nodoc:
+ def code ; 404 ; end
+ end
+
+ # Methods available to routes, before filters, and views.
+ module Helpers
+ # Set or retrieve the response status code.
+ def status(value=nil)
+ response.status = value if value
+ response.status
+ end
+
+ # Set or retrieve the response body. When a block is given,
+ # evaluation is deferred until the body is read with #each.
+ def body(value=nil, &block)
+ if block_given?
+ def block.each ; yield call ; end
+ response.body = block
+ else
+ response.body = value
+ end
+ end
+
+ # Halt processing and redirect to the URI provided.
+ def redirect(uri, *args)
+ status 302
+ response['Location'] = uri
+ halt(*args)
+ end
+
+ # Halt processing and return the error status provided.
+ def error(code, body=nil)
+ code, body = 500, code.to_str if code.respond_to? :to_str
+ response.body = body unless body.nil?
+ halt code
+ end
+
+ # Halt processing and return a 404 Not Found.
+ def not_found(body=nil)
+ error 404, body
+ end
+
+ # Set multiple response headers with Hash.
+ def headers(hash=nil)
+ response.headers.merge! hash if hash
+ response.headers
+ end
+
+ # Access the underlying Rack session.
+ def session
+ env['rack.session'] ||= {}
+ end
+
+ # Look up a media type by file extension in Rack's mime registry.
+ def media_type(type)
+ Base.media_type(type)
+ end
+
+ # Set the Content-Type of the response body given a media type or file
+ # extension.
+ def content_type(type, params={})
+ media_type = self.media_type(type)
+ fail "Unknown media type: %p" % type if media_type.nil?
+ if params.any?
+ params = params.collect { |kv| "%s=%s" % kv }.join(', ')
+ response['Content-Type'] = [media_type, params].join(";")
+ else
+ response['Content-Type'] = media_type
+ end
+ end
+
+ # Set the Content-Disposition to "attachment" with the specified filename,
+ # instructing the user agents to prompt to save.
+ def attachment(filename=nil)
+ response['Content-Disposition'] = 'attachment'
+ if filename
+ params = '; filename="%s"' % File.basename(filename)
+ response['Content-Disposition'] << params
+ end
+ end
+
+ # Use the contents of the file at +path+ as the response body.
+ def send_file(path, opts={})
+ stat = File.stat(path)
+ last_modified stat.mtime
+
+ content_type media_type(opts[:type]) ||
+ media_type(File.extname(path)) ||
+ response['Content-Type'] ||
+ 'application/octet-stream'
+
+ response['Content-Length'] ||= (opts[:length] || stat.size).to_s
+
+ if opts[:disposition] == 'attachment' || opts[:filename]
+ attachment opts[:filename] || path
+ elsif opts[:disposition] == 'inline'
+ response['Content-Disposition'] = 'inline'
+ end
+
+ halt StaticFile.open(path, 'rb')
+ rescue Errno::ENOENT
+ not_found
+ end
+
+ # Rack response body used to deliver static files. The file contents are
+ # generated iteratively in 8K chunks.
+ class StaticFile < ::File #:nodoc:
+ alias_method :to_path, :path
+ def each
+ rewind
+ while buf = read(8192)
+ yield buf
+ end
+ end
+ end
+
+ # Set the last modified time of the resource (HTTP 'Last-Modified' header)
+ # and halt if conditional GET matches. The +time+ argument is a Time,
+ # DateTime, or other object that responds to +to_time+.
+ #
+ # When the current request includes an 'If-Modified-Since' header that
+ # matches the time specified, execution is immediately halted with a
+ # '304 Not Modified' response.
+ def last_modified(time)
+ time = time.to_time if time.respond_to?(:to_time)
+ time = time.httpdate if time.respond_to?(:httpdate)
+ response['Last-Modified'] = time
+ halt 304 if time == request.env['HTTP_IF_MODIFIED_SINCE']
+ time
+ end
+
+ # Set the response entity tag (HTTP 'ETag' header) and halt if conditional
+ # GET matches. The +value+ argument is an identifier that uniquely
+ # identifies the current version of the resource. The +strength+ argument
+ # indicates whether the etag should be used as a :strong (default) or :weak
+ # cache validator.
+ #
+ # When the current request includes an 'If-None-Match' header with a
+ # matching etag, execution is immediately halted. If the request method is
+ # GET or HEAD, a '304 Not Modified' response is sent.
+ def etag(value, kind=:strong)
+ raise TypeError, ":strong or :weak expected" if ![:strong,:weak].include?(kind)
+ value = '"%s"' % value
+ value = 'W/' + value if kind == :weak
+ response['ETag'] = value
+
+ # Conditional GET check
+ if etags = env['HTTP_IF_NONE_MATCH']
+ etags = etags.split(/\s*,\s*/)
+ halt 304 if etags.include?(value) || etags.include?('*')
+ end
+ end
+
+ ## Sugar for redirect (example: redirect back)
+ def back ; request.referer ; end
+
+ end
+
+ # Template rendering methods. Each method takes a the name of a template
+ # to render as a Symbol and returns a String with the rendered output,
+ # as well as an optional hash with additional options.
+ #
+ # `template` is either the name or path of the template as symbol
+ # (Use `:'subdir/myview'` for views in subdirectories), or a string
+ # that will be rendered.
+ #
+ # Possible options are:
+ # :layout If set to false, no layout is rendered, otherwise
+ # the specified layout is used (Ignored for `sass`)
+ # :locals A hash with local variables that should be available
+ # in the template
+ module Templates
+ def erb(template, options={}, locals={})
+ render :erb, template, options, locals
+ end
+
+ def haml(template, options={}, locals={})
+ render :haml, template, options, locals
+ end
+
+ def sass(template, options={}, locals={})
+ options[:layout] = false
+ render :sass, template, options, locals
+ end
+
+ def builder(template=nil, options={}, locals={}, &block)
+ options, template = template, nil if template.is_a?(Hash)
+ template = lambda { block } if template.nil?
+ render :builder, template, options, locals
+ end
+
+ private
+ def render(engine, template, options={}, locals={})
+ # merge app-level options
+ options = self.class.send(engine).merge(options) if self.class.respond_to?(engine)
+
+ # extract generic options
+ layout = options.delete(:layout)
+ layout = :layout if layout.nil? || layout == true
+ views = options.delete(:views) || self.class.views || "./views"
+ locals = options.delete(:locals) || locals || {}
+
+ # render template
+ data, options[:filename], options[:line] = lookup_template(engine, template, views)
+ output = __send__("render_#{engine}", template, data, options, locals)
+
+ # render layout
+ if layout
+ data, options[:filename], options[:line] = lookup_layout(engine, layout, views)
+ if data
+ output = __send__("render_#{engine}", layout, data, options, locals) { output }
+ end
+ end
+
+ output
+ end
+
+ def lookup_template(engine, template, views_dir, filename = nil, line = nil)
+ case template
+ when Symbol
+ load_template(engine, template, views_dir, options)
+ when Proc
+ filename, line = self.class.caller_locations.first if filename.nil?
+ [template.call, filename, line.to_i]
+ when String
+ filename, line = self.class.caller_locations.first if filename.nil?
+ [template, filename, line.to_i]
+ else
+ raise ArgumentError
+ end
+ end
+
+ def load_template(engine, template, views_dir, options={})
+ base = self.class
+ while base.respond_to?(:templates)
+ if cached = base.templates[template]
+ return lookup_template(engine, cached[:template], views_dir, cached[:filename], cached[:line])
+ else
+ base = base.superclass
+ end
+ end
+
+ # If no template exists in the cache, try loading from disk.
+ path = ::File.join(views_dir, "#{template}.#{engine}")
+ [ ::File.read(path), path, 1 ]
+ end
+
+ def lookup_layout(engine, template, views_dir)
+ lookup_template(engine, template, views_dir)
+ rescue Errno::ENOENT
+ nil
+ end
+
+ def render_erb(template, data, options, locals, &block)
+ original_out_buf = defined?(@_out_buf) && @_out_buf
+ data = data.call if data.kind_of? Proc
+
+ instance = ::ERB.new(data, nil, nil, '@_out_buf')
+ locals_assigns = locals.to_a.collect { |k,v| "#{k} = locals[:#{k}]" }
+
+ filename = options.delete(:filename) || '(__ERB__)'
+ line = options.delete(:line) || 1
+ line -= 1 if instance.src =~ /^#coding:/
+
+ render_binding = binding
+ eval locals_assigns.join("\n"), render_binding
+ eval instance.src, render_binding, filename, line
+ @_out_buf, result = original_out_buf, @_out_buf
+ result
+ end
+
+ def render_haml(template, data, options, locals, &block)
+ ::Haml::Engine.new(data, options).render(self, locals, &block)
+ end
+
+ def render_sass(template, data, options, locals, &block)
+ ::Sass::Engine.new(data, options).render
+ end
+
+ def render_builder(template, data, options, locals, &block)
+ options = { :indent => 2 }.merge(options)
+ filename = options.delete(:filename) || '<BUILDER>'
+ line = options.delete(:line) || 1
+ xml = ::Builder::XmlMarkup.new(options)
+ if data.respond_to?(:to_str)
+ eval data.to_str, binding, filename, line
+ elsif data.kind_of?(Proc)
+ data.call(xml)
+ end
+ xml.target!
+ end
+ end
+
+ # Base class for all Sinatra applications and middleware.
+ class Base
+ include Rack::Utils
+ include Helpers
+ include Templates
+
+ attr_accessor :app
+
+ def initialize(app=nil)
+ @app = app
+ yield self if block_given?
+ end
+
+ # Rack call interface.
+ def call(env)
+ dup.call!(env)
+ end
+
+ attr_accessor :env, :request, :response, :params
+
+ def call!(env)
+ @env = env
+ @request = Request.new(env)
+ @response = Response.new
+ @params = indifferent_params(@request.params)
+
+ invoke { dispatch! }
+ invoke { error_block!(response.status) }
+
+ status, header, body = @response.finish
+
+ # Never produce a body on HEAD requests. Do retain the Content-Length
+ # unless it's "0", in which case we assume it was calculated erroneously
+ # for a manual HEAD response and remove it entirely.
+ if @env['REQUEST_METHOD'] == 'HEAD'
+ body = []
+ header.delete('Content-Length') if header['Content-Length'] == '0'
+ end
+
+ [status, header, body]
+ end
+
+ # Access options defined with Base.set.
+ def options
+ self.class
+ end
+
+ # Exit the current block, halts any further processing
+ # of the request, and returns the specified response.
+ def halt(*response)
+ response = response.first if response.length == 1
+ throw :halt, response
+ end
+
+ # Pass control to the next matching route.
+ # If there are no more matching routes, Sinatra will
+ # return a 404 response.
+ def pass
+ throw :pass
+ end
+
+ # Forward the request to the downstream app -- middleware only.
+ def forward
+ fail "downstream app not set" unless @app.respond_to? :call
+ status, headers, body = @app.call(@request.env)
+ @response.status = status
+ @response.body = body
+ @response.headers.merge! headers
+ nil
+ end
+
+ private
+ # Run before filters defined on the class and all superclasses.
+ def filter!(base=self.class)
+ filter!(base.superclass) if base.superclass.respond_to?(:filters)
+ base.filters.each { |block| instance_eval(&block) }
+ end
+
+ # Run routes defined on the class and all superclasses.
+ def route!(base=self.class)
+ if routes = base.routes[@request.request_method]
+ original_params = @params
+ path = unescape(@request.path_info)
+
+ routes.each do |pattern, keys, conditions, block|
+ if match = pattern.match(path)
+ values = match.captures.to_a
+ params =
+ if keys.any?
+ keys.zip(values).inject({}) do |hash,(k,v)|
+ if k == 'splat'
+ (hash[k] ||= []) << v
+ else
+ hash[k] = v
+ end
+ hash
+ end
+ elsif values.any?
+ {'captures' => values}
+ else
+ {}
+ end
+ @params = original_params.merge(params)
+ @block_params = values
+
+ catch(:pass) do
+ conditions.each { |cond|
+ throw :pass if instance_eval(&cond) == false }
+ route_eval(&block)
+ end
+ end
+ end
+
+ @params = original_params
+ end
+
+ # Run routes defined in superclass.
+ if base.superclass.respond_to?(:routes)
+ route! base.superclass
+ return
+ end
+
+ route_missing
+ end
+
+ # Run a route block and throw :halt with the result.
+ def route_eval(&block)
+ throw :halt, instance_eval(&block)
+ end
+
+ # No matching route was found or all routes passed. The default
+ # implementation is to forward the request downstream when running
+ # as middleware (@app is non-nil); when no downstream app is set, raise
+ # a NotFound exception. Subclasses can override this method to perform
+ # custom route miss logic.
+ def route_missing
+ if @app
+ forward
+ else
+ raise NotFound
+ end
+ end
+
+ # Attempt to serve static files from public directory. Throws :halt when
+ # a matching file is found, returns nil otherwise.
+ def static!
+ return if (public_dir = options.public).nil?
+ public_dir = File.expand_path(public_dir)
+
+ path = File.expand_path(public_dir + unescape(request.path_info))
+ return if path[0, public_dir.length] != public_dir
+ return unless File.file?(path)
+
+ send_file path, :disposition => nil
+ end
+
+ # Enable string or symbol key access to the nested params hash.
+ def indifferent_params(params)
+ params = indifferent_hash.merge(params)
+ params.each do |key, value|
+ next unless value.is_a?(Hash)
+ params[key] = indifferent_params(value)
+ end
+ end
+
+ def indifferent_hash
+ Hash.new {|hash,key| hash[key.to_s] if Symbol === key }
+ end
+
+ # Run the block with 'throw :halt' support and apply result to the response.
+ def invoke(&block)
+ res = catch(:halt) { instance_eval(&block) }
+ return if res.nil?
+
+ case
+ when res.respond_to?(:to_str)
+ @response.body = [res]
+ when res.respond_to?(:to_ary)
+ res = res.to_ary
+ if Fixnum === res.first
+ if res.length == 3
+ @response.status, headers, body = res
+ @response.body = body if body
+ headers.each { |k, v| @response.headers[k] = v } if headers
+ elsif res.length == 2
+ @response.status = res.first
+ @response.body = res.last
+ else
+ raise TypeError, "#{res.inspect} not supported"
+ end
+ else
+ @response.body = res
+ end
+ when res.respond_to?(:each)
+ @response.body = res
+ when (100...599) === res
+ @response.status = res
+ end
+
+ res
+ end
+
+ # Dispatch a request with error handling.
+ def dispatch!
+ filter!
+ static! if options.static? && (request.get? || request.head?)
+ route!
+ rescue NotFound => boom
+ handle_not_found!(boom)
+ rescue ::Exception => boom
+ handle_exception!(boom)
+ end
+
+ def handle_not_found!(boom)
+ @env['sinatra.error'] = boom
+ @response.status = 404
+ @response.body = ['<h1>Not Found</h1>']
+ error_block! boom.class, NotFound
+ end
+
+ def handle_exception!(boom)
+ @env['sinatra.error'] = boom
+
+ dump_errors!(boom) if options.dump_errors?
+ raise boom if options.raise_errors? || options.show_exceptions?
+
+ @response.status = 500
+ error_block! boom.class, Exception
+ end
+
+ # Find an custom error block for the key(s) specified.
+ def error_block!(*keys)
+ keys.each do |key|
+ base = self.class
+ while base.respond_to?(:errors)
+ if block = base.errors[key]
+ # found a handler, eval and return result
+ res = instance_eval(&block)
+ return res
+ else
+ base = base.superclass
+ end
+ end
+ end
+ nil
+ end
+
+ def dump_errors!(boom)
+ backtrace = clean_backtrace(boom.backtrace)
+ msg = ["#{boom.class} - #{boom.message}:",
+ *backtrace].join("\n ")
+ @env['rack.errors'].write(msg)
+ end
+
+ def clean_backtrace(trace)
+ return trace unless options.clean_trace?
+
+ trace.reject { |line|
+ line =~ /lib\/sinatra.*\.rb/ ||
+ (defined?(Gem) && line.include?(Gem.dir))
+ }.map! { |line| line.gsub(/^\.\//, '') }
+ end
+
+ class << self
+ attr_reader :routes, :filters, :templates, :errors
+
+ def reset!
+ @conditions = []
+ @routes = {}
+ @filters = []
+ @templates = {}
+ @errors = {}
+ @middleware = []
+ @prototype = nil
+ @extensions = []
+ end
+
+ # Extension modules registered on this class and all superclasses.
+ def extensions
+ if superclass.respond_to?(:extensions)
+ (@extensions + superclass.extensions).uniq
+ else
+ @extensions
+ end
+ end
+
+ # Middleware used in this class and all superclasses.
+ def middleware
+ if superclass.respond_to?(:middleware)
+ superclass.middleware + @middleware
+ else
+ @middleware
+ end
+ end
+
+ # Sets an option to the given value. If the value is a proc,
+ # the proc will be called every time the option is accessed.
+ def set(option, value=self)
+ if value.kind_of?(Proc)
+ metadef(option, &value)
+ metadef("#{option}?") { !!__send__(option) }
+ metadef("#{option}=") { |val| set(option, Proc.new{val}) }
+ elsif value == self && option.respond_to?(:to_hash)
+ option.to_hash.each { |k,v| set(k, v) }
+ elsif respond_to?("#{option}=")
+ __send__ "#{option}=", value
+ else
+ set option, Proc.new{value}
+ end
+ self
+ end
+
+ # Same as calling `set :option, true` for each of the given options.
+ def enable(*opts)
+ opts.each { |key| set(key, true) }
+ end
+
+ # Same as calling `set :option, false` for each of the given options.
+ def disable(*opts)
+ opts.each { |key| set(key, false) }
+ end
+
+ # Define a custom error handler. Optionally takes either an Exception
+ # class, or an HTTP status code to specify which errors should be
+ # handled.
+ def error(codes=Exception, &block)
+ if codes.respond_to? :each
+ codes.each { |err| error(err, &block) }
+ else
+ @errors[codes] = block
+ end
+ end
+
+ # Sugar for `error(404) { ... }`
+ def not_found(&block)
+ error 404, &block
+ end
+
+ # Define a named template. The block must return the template source.
+ def template(name, &block)
+ filename, line = caller_locations.first
+ templates[name] = { :filename => filename, :line => line, :template => block }
+ end
+
+ # Define the layout template. The block must return the template source.
+ def layout(name=:layout, &block)
+ template name, &block
+ end
+
+ # Load embeded templates from the file; uses the caller's __FILE__
+ # when no file is specified.
+ def use_in_file_templates!(file=nil)
+ file ||= caller_files.first
+ app, data =
+ ::IO.read(file).split(/^__END__$/, 2) rescue nil
+
+ if data
+ data.gsub!(/\r\n/, "\n")
+ lines = app.count("\n") + 1
+ template = nil
+ data.each_line do |line|
+ lines += 1
+ if line =~ /^@@\s*(.*)/
+ template = ''
+ templates[$1.to_sym] = { :filename => file, :line => lines, :template => template }
+ elsif template
+ template << line
+ end
+ end
+ end
+ end
+
+ # Look up a media type by file extension in Rack's mime registry.
+ def media_type(type)
+ return type if type.nil? || type.to_s.include?('/')
+ type = ".#{type}" unless type.to_s[0] == ?.
+ Rack::Mime.mime_type(type, nil)
+ end
+
+ # Define a before filter. Filters are run before all requests
+ # within the same context as route handlers and may access/modify the
+ # request and response.
+ def before(&block)
+ @filters << block
+ end
+
+ # Add a route condition. The route is considered non-matching when the
+ # block returns false.
+ def condition(&block)
+ @conditions << block
+ end
+
+ private
+ def host_name(pattern)
+ condition { pattern === request.host }
+ end
+
+ def user_agent(pattern)
+ condition {
+ if request.user_agent =~ pattern
+ @params[:agent] = $~[1..-1]
+ true
+ else
+ false
+ end
+ }
+ end
+ alias_method :agent, :user_agent
+
+ def provides(*types)
+ types = [types] unless types.kind_of? Array
+ types.map!{|t| media_type(t)}
+
+ condition {
+ matching_types = (request.accept & types)
+ unless matching_types.empty?
+ response.headers['Content-Type'] = matching_types.first
+ true
+ else
+ false
+ end
+ }
+ end
+
+ public
+ # Defining a `GET` handler also automatically defines
+ # a `HEAD` handler.
+ def get(path, opts={}, &block)
+ conditions = @conditions.dup
+ route('GET', path, opts, &block)
+
+ @conditions = conditions
+ route('HEAD', path, opts, &block)
+ end
+
+ def put(path, opts={}, &bk); route 'PUT', path, opts, &bk end
+ def post(path, opts={}, &bk); route 'POST', path, opts, &bk end
+ def delete(path, opts={}, &bk); route 'DELETE', path, opts, &bk end
+ def head(path, opts={}, &bk); route 'HEAD', path, opts, &bk end
+
+ private
+ def route(verb, path, options={}, &block)
+ # Because of self.options.host
+ host_name(options.delete(:host)) if options.key?(:host)
+
+ options.each {|option, args| send(option, *args)}
+
+ pattern, keys = compile(path)
+ conditions, @conditions = @conditions, []
+
+ define_method "#{verb} #{path}", &block
+ unbound_method = instance_method("#{verb} #{path}")
+ block =
+ if block.arity != 0
+ lambda { unbound_method.bind(self).call(*@block_params) }
+ else
+ lambda { unbound_method.bind(self).call }
+ end
+
+ invoke_hook(:route_added, verb, path, block)
+
+ (@routes[verb] ||= []).
+ push([pattern, keys, conditions, block]).last
+ end
+
+ def invoke_hook(name, *args)
+ extensions.each { |e| e.send(name, *args) if e.respond_to?(name) }
+ end
+
+ def compile(path)
+ keys = []
+ if path.respond_to? :to_str
+ special_chars = %w{. + ( )}
+ pattern =
+ path.to_str.gsub(/((:\w+)|[\*#{special_chars.join}])/) do |match|
+ case match
+ when "*"
+ keys << 'splat'
+ "(.*?)"
+ when *special_chars
+ Regexp.escape(match)
+ else
+ keys << $2[1..-1]
+ "([^/?&#]+)"
+ end
+ end
+ [/^#{pattern}$/, keys]
+ elsif path.respond_to?(:keys) && path.respond_to?(:match)
+ [path, path.keys]
+ elsif path.respond_to? :match
+ [path, keys]
+ else
+ raise TypeError, path
+ end
+ end
+
+ public
+ # Makes the methods defined in the block and in the Modules given
+ # in `extensions` available to the handlers and templates
+ def helpers(*extensions, &block)
+ class_eval(&block) if block_given?
+ include(*extensions) if extensions.any?
+ end
+
+ def register(*extensions, &block)
+ extensions << Module.new(&block) if block_given?
+ @extensions += extensions
+ extensions.each do |extension|
+ extend extension
+ extension.registered(self) if extension.respond_to?(:registered)
+ end
+ end
+
+ def development?; environment == :development end
+ def production?; environment == :production end
+ def test?; environment == :test end
+
+ # Set configuration options for Sinatra and/or the app.
+ # Allows scoping of settings for certain environments.
+ def configure(*envs, &block)
+ yield self if envs.empty? || envs.include?(environment.to_sym)
+ end
+
+ # Use the specified Rack middleware
+ def use(middleware, *args, &block)
+ @prototype = nil
+ @middleware << [middleware, args, block]
+ end
+
+ # Run the Sinatra app as a self-hosted server using
+ # Thin, Mongrel or WEBrick (in that order)
+ def run!(options={})
+ set options
+ handler = detect_rack_handler
+ handler_name = handler.name.gsub(/.*::/, '')
+ puts "== Sinatra/#{Sinatra::VERSION} has taken the stage " +
+ "on #{port} for #{environment} with backup from #{handler_name}" unless handler_name =~/cgi/i
+ handler.run self, :Host => host, :Port => port do |server|
+ trap(:INT) do
+ ## Use thins' hard #stop! if available, otherwise just #stop
+ server.respond_to?(:stop!) ? server.stop! : server.stop
+ puts "\n== Sinatra has ended his set (crowd applauds)" unless handler_name =~/cgi/i
+ end
+ end
+ rescue Errno::EADDRINUSE => e
+ puts "== Someone is already performing on port #{port}!"
+ end
+
+ # The prototype instance used to process requests.
+ def prototype
+ @prototype ||= new
+ end
+
+ # Create a new instance of the class fronted by its middleware
+ # pipeline. The object is guaranteed to respond to #call but may not be
+ # an instance of the class new was called on.
+ def new(*args, &bk)
+ builder = Rack::Builder.new
+ builder.use Rack::Session::Cookie if sessions? && !test?
+ builder.use Rack::CommonLogger if logging?
+ builder.use Rack::MethodOverride if methodoverride?
+ builder.use ShowExceptions if show_exceptions?
+ middleware.each { |c,a,b| builder.use(c, *a, &b) }
+
+ builder.run super
+ builder.to_app
+ end
+
+ def call(env)
+ synchronize { prototype.call(env) }
+ end
+
+ private
+ def detect_rack_handler
+ servers = Array(self.server)
+ servers.each do |server_name|
+ begin
+ return Rack::Handler.get(server_name.downcase)
+ rescue LoadError
+ rescue NameError
+ end
+ end
+ fail "Server handler (#{servers.join(',')}) not found."
+ end
+
+ def inherited(subclass)
+ subclass.reset!
+ super
+ end
+
+ @@mutex = Mutex.new
+ def synchronize(&block)
+ if lock?
+ @@mutex.synchronize(&block)
+ else
+ yield
+ end
+ end
+
+ def metadef(message, &block)
+ (class << self; self; end).
+ send :define_method, message, &block
+ end
+
+ public
+ CALLERS_TO_IGNORE = [
+ /lib\/sinatra.*\.rb$/, # all sinatra code
+ /\(.*\)/, # generated code
+ /custom_require\.rb$/, # rubygems require hacks
+ /active_support/, # active_support require hacks
+ ]
+
+ # add rubinius (and hopefully other VM impls) ignore patterns ...
+ CALLERS_TO_IGNORE.concat(RUBY_IGNORE_CALLERS) if defined?(RUBY_IGNORE_CALLERS)
+
+ # Like Kernel#caller but excluding certain magic entries and without
+ # line / method information; the resulting array contains filenames only.
+ def caller_files
+ caller_locations.
+ map { |file,line| file }
+ end
+
+ def caller_locations
+ caller(1).
+ map { |line| line.split(/:(?=\d|in )/)[0,2] }.
+ reject { |file,line| CALLERS_TO_IGNORE.any? { |pattern| file =~ pattern } }
+ end
+ end
+
+ reset!
+
+ set :raise_errors, true
+ set :dump_errors, false
+ set :clean_trace, true
+ set :show_exceptions, false
+ set :sessions, false
+ set :logging, false
+ set :methodoverride, false
+ set :static, false
+ set :environment, (ENV['RACK_ENV'] || :development).to_sym
+
+ set :run, false
+ set :server, %w[thin mongrel webrick]
+ set :host, '0.0.0.0'
+ set :port, 4567
+
+ set :app_file, nil
+ set :root, Proc.new { app_file && File.expand_path(File.dirname(app_file)) }
+ set :views, Proc.new { root && File.join(root, 'views') }
+ set :public, Proc.new { root && File.join(root, 'public') }
+ set :lock, false
+
+ error ::Exception do
+ response.status = 500
+ content_type 'text/html'
+ '<h1>Internal Server Error</h1>'
+ end
+
+ configure :development do
+ get '/__sinatra__/:image.png' do
+ filename = File.dirname(__FILE__) + "/images/#{params[:image]}.png"
+ content_type :png
+ send_file filename
+ end
+
+ error NotFound do
+ content_type 'text/html'
+
+ (<<-HTML).gsub(/^ {8}/, '')
+ <!DOCTYPE html>
+ <html>
+ <head>
+ <style type="text/css">
+ body { text-align:center;font-family:helvetica,arial;font-size:22px;
+ color:#888;margin:20px}
+ #c {margin:0 auto;width:500px;text-align:left}
+ </style>
+ </head>
+ <body>
+ <h2>Sinatra doesn't know this ditty.</h2>
+ <img src='/__sinatra__/404.png'>
+ <div id="c">
+ Try this:
+ <pre>#{request.request_method.downcase} '#{request.path_info}' do\n "Hello World"\nend</pre>
+ </div>
+ </body>
+ </html>
+ HTML
+ end
+ end
+ end
+
+ # Base class for classic style (top-level) applications.
+ class Default < Base
+ set :raise_errors, Proc.new { test? }
+ set :show_exceptions, Proc.new { development? }
+ set :dump_errors, true
+ set :sessions, false
+ set :logging, Proc.new { ! test? }
+ set :methodoverride, true
+ set :static, true
+ set :run, Proc.new { ! test? }
+
+ def self.register(*extensions, &block) #:nodoc:
+ added_methods = extensions.map {|m| m.public_instance_methods }.flatten
+ Delegator.delegate(*added_methods)
+ super(*extensions, &block)
+ end
+ end
+
+ # The top-level Application. All DSL methods executed on main are delegated
+ # to this class.
+ class Application < Default
+ end
+
+ # Sinatra delegation mixin. Mixing this module into an object causes all
+ # methods to be delegated to the Sinatra::Application class. Used primarily
+ # at the top-level.
+ module Delegator #:nodoc:
+ def self.delegate(*methods)
+ methods.each do |method_name|
+ eval <<-RUBY, binding, '(__DELEGATE__)', 1
+ def #{method_name}(*args, &b)
+ ::Sinatra::Application.send(#{method_name.inspect}, *args, &b)
+ end
+ private #{method_name.inspect}
+ RUBY
+ end
+ end
+
+ delegate :get, :put, :post, :delete, :head, :template, :layout, :before,
+ :error, :not_found, :configures, :configure, :set, :set_option,
+ :set_options, :enable, :disable, :use, :development?, :test?,
+ :production?, :use_in_file_templates!, :helpers
+ end
+
+ # Create a new Sinatra application. The block is evaluated in the new app's
+ # class scope.
+ def self.new(base=Base, options={}, &block)
+ base = Class.new(base)
+ base.send :class_eval, &block if block_given?
+ base
+ end
+
+ # Extend the top-level DSL with the modules provided.
+ def self.register(*extensions, &block)
+ Default.register(*extensions, &block)
+ end
+
+ # Include the helper modules provided in Sinatra's request context.
+ def self.helpers(*extensions, &block)
+ Default.helpers(*extensions, &block)
+ end
+end
diff --git a/vendor/sinatra/lib/sinatra/images/404.png b/vendor/sinatra/lib/sinatra/images/404.png
new file mode 100644
index 0000000..902110e
Binary files /dev/null and b/vendor/sinatra/lib/sinatra/images/404.png differ
diff --git a/vendor/sinatra/lib/sinatra/images/500.png b/vendor/sinatra/lib/sinatra/images/500.png
new file mode 100644
index 0000000..57c84c3
Binary files /dev/null and b/vendor/sinatra/lib/sinatra/images/500.png differ
diff --git a/vendor/sinatra/lib/sinatra/main.rb b/vendor/sinatra/lib/sinatra/main.rb
new file mode 100644
index 0000000..ee7f5b8
--- /dev/null
+++ b/vendor/sinatra/lib/sinatra/main.rb
@@ -0,0 +1,35 @@
+require 'sinatra/base'
+
+module Sinatra
+ class Default < Base
+
+ # we assume that the first file that requires 'sinatra' is the
+ # app_file. all other path related options are calculated based
+ # on this path by default.
+ set :app_file, caller_files.first || $0
+
+ set :run, Proc.new { $0 == app_file }
+
+ if run? && ARGV.any?
+ require 'optparse'
+ OptionParser.new { |op|
+ op.on('-x') { set :lock, true }
+ op.on('-e env') { |val| set :environment, val.to_sym }
+ op.on('-s server') { |val| set :server, val }
+ op.on('-p port') { |val| set :port, val.to_i }
+ }.parse!(ARGV.dup)
+ end
+ end
+end
+
+include Sinatra::Delegator
+
+def mime(ext, type)
+ ext = ".#{ext}" unless ext.to_s[0] == ?.
+ Rack::Mime::MIME_TYPES[ext.to_s] = type
+end
+
+at_exit do
+ raise $! if $!
+ Sinatra::Application.run! if Sinatra::Application.run?
+end
diff --git a/vendor/sinatra/lib/sinatra/showexceptions.rb b/vendor/sinatra/lib/sinatra/showexceptions.rb
new file mode 100644
index 0000000..9f78768
--- /dev/null
+++ b/vendor/sinatra/lib/sinatra/showexceptions.rb
@@ -0,0 +1,303 @@
+require 'rack/showexceptions'
+
+module Sinatra
+ class ShowExceptions < Rack::ShowExceptions
+ def initialize(app)
+ @app = app
+ @template = ERB.new(TEMPLATE)
+ end
+
+ def frame_class(frame)
+ if frame.filename =~ /lib\/sinatra.*\.rb/
+ "framework"
+ elsif (defined?(Gem) && frame.filename.include?(Gem.dir)) ||
+ frame.filename =~ /\/bin\/(\w+)$/
+ "system"
+ else
+ "app"
+ end
+ end
+
+TEMPLATE = <<HTML
+<!DOCTYPE html>
+<html>
+<head>
+ <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
+ <title><%=h exception.class %> at <%=h path %></title>
+
+ <script type="text/javascript">
+ //<!--
+ function toggle(id) {
+ var pre = document.getElementById("pre-" + id);
+ var post = document.getElementById("post-" + id);
+ var context = document.getElementById("context-" + id);
+
+ if (pre.style.display == 'block') {
+ pre.style.display = 'none';
+ post.style.display = 'none';
+ context.style.background = "none";
+ } else {
+ pre.style.display = 'block';
+ post.style.display = 'block';
+ context.style.background = "#fffed9";
+ }
+ }
+
+ function toggleBacktrace(){
+ var bt = document.getElementById("backtrace");
+ var toggler = document.getElementById("expando");
+
+ if (bt.className == 'condensed') {
+ bt.className = 'expanded';
+ toggler.innerHTML = "(condense)";
+ } else {
+ bt.className = 'condensed';
+ toggler.innerHTML = "(expand)";
+ }
+ }
+ //-->
+ </script>
+
+<style type="text/css" media="screen">
+ * {margin: 0; padding: 0; border: 0; outline: 0;}
+ div.clear {clear: both;}
+ body {background: #EEEEEE; margin: 0; padding: 0;
+ font-family: 'Lucida Grande', 'Lucida Sans Unicode',
+ 'Garuda';}
+ code {font-family: 'Lucida Console', monospace;
+ font-size: 12px;}
+ li {height: 18px;}
+ ul {list-style: none; margin: 0; padding: 0;}
+ ol:hover {cursor: pointer;}
+ ol li {white-space: pre;}
+ #explanation {font-size: 12px; color: #666666;
+ margin: 20px 0 0 100px;}
+/* WRAP */
+ #wrap {width: 860px; background: #FFFFFF; margin: 0 auto;
+ padding: 30px 50px 20px 50px;
+ border-left: 1px solid #DDDDDD;
+ border-right: 1px solid #DDDDDD;}
+/* HEADER */
+ #header {margin: 0 auto 25px auto;}
+ #header img {float: left;}
+ #header #summary {float: left; margin: 12px 0 0 20px; width:520px;
+ font-family: 'Lucida Grande', 'Lucida Sans Unicode';}
+ h1 {margin: 0; font-size: 36px; color: #981919;}
+ h2 {margin: 0; font-size: 22px; color: #333333;}
+ #header ul {margin: 0; font-size: 12px; color: #666666;}
+ #header ul li strong{color: #444444;}
+ #header ul li {display: inline; padding: 0 10px;}
+ #header ul li.first {padding-left: 0;}
+ #header ul li.last {border: 0; padding-right: 0;}
+/* BODY */
+ #backtrace,
+ #get,
+ #post,
+ #cookies,
+ #rack {width: 860px; margin: 0 auto 10px auto;}
+ p#nav {float: right; font-size: 14px;}
+/* BACKTRACE */
+ a#expando {float: left; padding-left: 5px; color: #666666;
+ font-size: 14px; text-decoration: none; cursor: pointer;}
+ a#expando:hover {text-decoration: underline;}
+ h3 {float: left; width: 100px; margin-bottom: 10px;
+ color: #981919; font-size: 14px; font-weight: bold;}
+ #nav a {color: #666666; text-decoration: none; padding: 0 5px;}
+ #backtrace li.frame-info {background: #f7f7f7; padding-left: 10px;
+ font-size: 12px; color: #333333;}
+ #backtrace ul {list-style-position: outside; border: 1px solid #E9E9E9;
+ border-bottom: 0;}
+ #backtrace ol {width: 808px; margin-left: 50px;
+ font: 10px 'Lucida Console', monospace; color: #666666;}
+ #backtrace ol li {border: 0; border-left: 1px solid #E9E9E9;
+ padding: 2px 0;}
+ #backtrace ol code {font-size: 10px; color: #555555; padding-left: 5px;}
+ #backtrace-ul li {border-bottom: 1px solid #E9E9E9; height: auto;
+ padding: 3px 0;}
+ #backtrace-ul .code {padding: 6px 0 4px 0;}
+ #backtrace.condensed .system,
+ #backtrace.condensed .framework {display:none;}
+/* REQUEST DATA */
+ p.no-data {padding-top: 2px; font-size: 12px; color: #666666;}
+ table.req {width: 760px; text-align: left; font-size: 12px;
+ color: #666666; padding: 0; border-spacing: 0;
+ border: 1px solid #EEEEEE; border-bottom: 0;
+ border-left: 0;}
+ table.req tr th {padding: 2px 10px; font-weight: bold;
+ background: #F7F7F7; border-bottom: 1px solid #EEEEEE;
+ border-left: 1px solid #EEEEEE;}
+ table.req tr td {padding: 2px 20px 2px 10px;
+ border-bottom: 1px solid #EEEEEE;
+ border-left: 1px solid #EEEEEE;}
+/* HIDE PRE/POST CODE AT START */
+ .pre-context,
+ .post-context {display: none;}
+</style>
+</head>
+<body>
+ <div id="wrap">
+ <div id="header">
+ <img src="/__sinatra__/500.png" alt="application error" />
+ <div id="summary">
+ <h1><strong><%=h exception.class %></strong> at <strong><%=h path %>
+ </strong></h1>
+ <h2><%=h exception.message %></h2>
+ <ul>
+ <li class="first"><strong>file:</strong> <code>
+ <%=h frames.first.filename.split("/").last %></code></li>
+ <li><strong>location:</strong> <code><%=h frames.first.function %>
+ </code></li>
+ <li class="last"><strong>line:
+ </strong> <%=h frames.first.lineno %></li>
+ </ul>
+ </div>
+ <div class="clear"></div>
+ </div>
+
+ <div id="backtrace" class='condensed'>
+ <h3>BACKTRACE</h3>
+ <p><a href="#" id="expando"
+ onclick="toggleBacktrace(); return false">(expand)</a></p>
+ <p id="nav"><strong>JUMP TO:</strong>
+ <a href="#get-info">GET</a>
+ <a href="#post-info">POST</a>
+ <a href="#cookie-info">COOKIES</a>
+ <a href="#env-info">ENV</a>
+ </p>
+ <div class="clear"></div>
+
+ <ul id="backtrace-ul">
+
+ <% id = 1 %>
+ <% frames.each do |frame| %>
+ <% if frame.context_line && frame.context_line != "#" %>
+
+ <li class="frame-info <%= frame_class(frame) %>">
+ <code><%=h frame.filename %></code> in
+ <code><strong><%=h frame.function %></strong></code>
+ </li>
+
+ <li class="code <%= frame_class(frame) %>">
+ <% if frame.pre_context %>
+ <ol start="<%=h frame.pre_context_lineno + 1 %>"
+ class="pre-context" id="pre-<%= id %>"
+ onclick="toggle(<%= id %>);">
+ <% frame.pre_context.each do |line| %>
+ <li class="pre-context-line"><code><%=h line %></code></li>
+ <% end %>
+ </ol>
+ <% end %>
+
+ <ol start="<%= frame.lineno %>" class="context" id="<%= id %>"
+ onclick="toggle(<%= id %>);">
+ <li class="context-line" id="context-<%= id %>"><code><%=
+ h frame.context_line %></code></li>
+ </ol>
+
+ <% if frame.post_context %>
+ <ol start="<%=h frame.lineno + 1 %>" class="post-context"
+ id="post-<%= id %>" onclick="toggle(<%= id %>);">
+ <% frame.post_context.each do |line| %>
+ <li class="post-context-line"><code><%=h line %></code></li>
+ <% end %>
+ </ol>
+ <% end %>
+ <div class="clear"></div>
+ </li>
+
+ <% end %>
+
+ <% id += 1 %>
+ <% end %>
+
+ </ul>
+ </div> <!-- /BACKTRACE -->
+
+ <div id="get">
+ <h3 id="get-info">GET</h3>
+ <% unless req.GET.empty? %>
+ <table class="req">
+ <tr>
+ <th>Variable</th>
+ <th>Value</th>
+ </tr>
+ <% req.GET.sort_by { |k, v| k.to_s }.each { |key, val| %>
+ <tr>
+ <td><%=h key %></td>
+ <td class="code"><div><%=h val.inspect %></div></td>
+ </tr>
+ <% } %>
+ </table>
+ <% else %>
+ <p class="no-data">No GET data.</p>
+ <% end %>
+ <div class="clear"></div>
+ </div> <!-- /GET -->
+
+ <div id="post">
+ <h3 id="post-info">POST</h3>
+ <% unless req.POST.empty? %>
+ <table class="req">
+ <tr>
+ <th>Variable</th>
+ <th>Value</th>
+ </tr>
+ <% req.POST.sort_by { |k, v| k.to_s }.each { |key, val| %>
+ <tr>
+ <td><%=h key %></td>
+ <td class="code"><div><%=h val.inspect %></div></td>
+ </tr>
+ <% } %>
+ </table>
+ <% else %>
+ <p class="no-data">No POST data.</p>
+ <% end %>
+ <div class="clear"></div>
+ </div> <!-- /POST -->
+
+ <div id="cookies">
+ <h3 id="cookie-info">COOKIES</h3>
+ <% unless req.cookies.empty? %>
+ <table class="req">
+ <tr>
+ <th>Variable</th>
+ <th>Value</th>
+ </tr>
+ <% req.cookies.each { |key, val| %>
+ <tr>
+ <td><%=h key %></td>
+ <td class="code"><div><%=h val.inspect %></div></td>
+ </tr>
+ <% } %>
+ </table>
+ <% else %>
+ <p class="no-data">No cookie data.</p>
+ <% end %>
+ <div class="clear"></div>
+ </div> <!-- /COOKIES -->
+
+ <div id="rack">
+ <h3 id="env-info">Rack ENV</h3>
+ <table class="req">
+ <tr>
+ <th>Variable</th>
+ <th>Value</th>
+ </tr>
+ <% env.sort_by { |k, v| k.to_s }.each { |key, val| %>
+ <tr>
+ <td><%=h key %></td>
+ <td class="code"><div><%=h val %></div></td>
+ </tr>
+ <% } %>
+ </table>
+ <div class="clear"></div>
+ </div> <!-- /RACK ENV -->
+
+ <p id="explanation">You're seeing this error because you use you have
+enabled the <code>show_exceptions</code> option.</p>
+ </div> <!-- /WRAP -->
+ </body>
+</html>
+HTML
+ end
+end
diff --git a/vendor/sinatra/sinatra.gemspec b/vendor/sinatra/sinatra.gemspec
new file mode 100644
index 0000000..d6d0191
--- /dev/null
+++ b/vendor/sinatra/sinatra.gemspec
@@ -0,0 +1,83 @@
+Gem::Specification.new do |s|
+ s.specification_version = 2 if s.respond_to? :specification_version=
+ s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
+
+ s.name = 'sinatra'
+ s.version = '0.10.1'
+ s.date = '2009-06-07'
+
+ s.description = "Classy web-development dressed in a DSL"
+ s.summary = "Classy web-development dressed in a DSL"
+
+ s.authors = ["Blake Mizerany", "Ryan Tomayko", "Simon Rozet"]
+ s.email = "sinatrarb@googlegroups.com"
+
+ # = MANIFEST =
+ s.files = %w[
+ AUTHORS
+ CHANGES
+ LICENSE
+ README.rdoc
+ Rakefile
+ lib/sinatra.rb
+ lib/sinatra/base.rb
+ lib/sinatra/images/404.png
+ lib/sinatra/images/500.png
+ lib/sinatra/main.rb
+ lib/sinatra/showexceptions.rb
+ sinatra.gemspec
+ test/base_test.rb
+ test/builder_test.rb
+ test/contest.rb
+ test/data/reload_app_file.rb
+ test/erb_test.rb
+ test/extensions_test.rb
+ test/filter_test.rb
+ test/haml_test.rb
+ test/helper.rb
+ test/helpers_test.rb
+ test/mapped_error_test.rb
+ test/middleware_test.rb
+ test/options_test.rb
+ test/render_backtrace_test.rb
+ test/request_test.rb
+ test/response_test.rb
+ test/result_test.rb
+ test/route_added_hook_test.rb
+ test/routing_test.rb
+ test/sass_test.rb
+ test/server_test.rb
+ test/sinatra_test.rb
+ test/static_test.rb
+ test/templates_test.rb
+ test/views/error.builder
+ test/views/error.erb
+ test/views/error.haml
+ test/views/error.sass
+ test/views/foo/hello.test
+ test/views/hello.builder
+ test/views/hello.erb
+ test/views/hello.haml
+ test/views/hello.sass
+ test/views/hello.test
+ test/views/layout2.builder
+ test/views/layout2.erb
+ test/views/layout2.haml
+ test/views/layout2.test
+ ]
+ # = MANIFEST =
+
+ s.test_files = s.files.select {|path| path =~ /^test\/.*_test.rb/}
+
+ s.extra_rdoc_files = %w[README.rdoc LICENSE]
+ s.add_dependency 'rack', '>= 1.0'
+ s.add_development_dependency 'shotgun', '>= 0.3', '< 1.0'
+ s.add_development_dependency 'rack-test', '>= 0.3.0'
+
+ s.has_rdoc = true
+ s.homepage = "http://sinatra.rubyforge.org"
+ s.rdoc_options = ["--line-numbers", "--inline-source", "--title", "Sinatra", "--main", "README.rdoc"]
+ s.require_paths = %w[lib]
+ s.rubyforge_project = 'sinatra'
+ s.rubygems_version = '1.1.1'
+end
diff --git a/vendor/sinatra/test/base_test.rb b/vendor/sinatra/test/base_test.rb
new file mode 100644
index 0000000..7a5d113
--- /dev/null
+++ b/vendor/sinatra/test/base_test.rb
@@ -0,0 +1,160 @@
+require File.dirname(__FILE__) + '/helper'
+
+class BaseTest < Test::Unit::TestCase
+ def test_default
+ assert true
+ end
+
+ describe 'Sinatra::Base subclasses' do
+ class TestApp < Sinatra::Base
+ get '/' do
+ 'Hello World'
+ end
+ end
+
+ it 'include Rack::Utils' do
+ assert TestApp.included_modules.include?(Rack::Utils)
+ end
+
+ it 'processes requests with #call' do
+ assert TestApp.respond_to?(:call)
+
+ request = Rack::MockRequest.new(TestApp)
+ response = request.get('/')
+ assert response.ok?
+ assert_equal 'Hello World', response.body
+ end
+
+ class TestApp < Sinatra::Base
+ get '/state' do
+ @foo ||= "new"
+ body = "Foo: #{@foo}"
+ @foo = 'discard'
+ body
+ end
+ end
+
+ it 'does not maintain state between requests' do
+ request = Rack::MockRequest.new(TestApp)
+ 2.times do
+ response = request.get('/state')
+ assert response.ok?
+ assert_equal 'Foo: new', response.body
+ end
+ end
+
+ it "passes the subclass to configure blocks" do
+ ref = nil
+ TestApp.configure { |app| ref = app }
+ assert_equal TestApp, ref
+ end
+
+ it "allows the configure block arg to be omitted and does not change context" do
+ context = nil
+ TestApp.configure { context = self }
+ assert_equal self, context
+ end
+ end
+
+ describe "Sinatra::Base as Rack middleware" do
+ app = lambda { |env|
+ headers = {'X-Downstream' => 'true'}
+ headers['X-Route-Missing'] = env['sinatra.route-missing'] || ''
+ [210, headers, ['Hello from downstream']] }
+
+ class TestMiddleware < Sinatra::Base
+ end
+
+ it 'creates a middleware that responds to #call with .new' do
+ middleware = TestMiddleware.new(app)
+ assert middleware.respond_to?(:call)
+ end
+
+ it 'exposes the downstream app' do
+ middleware = TestMiddleware.new(app)
+ assert_same app, middleware.app
+ end
+
+ class TestMiddleware < Sinatra::Base
+ def route_missing
+ env['sinatra.route-missing'] = '1'
+ super
+ end
+
+ get '/' do
+ 'Hello from middleware'
+ end
+ end
+
+ middleware = TestMiddleware.new(app)
+ request = Rack::MockRequest.new(middleware)
+
+ it 'intercepts requests' do
+ response = request.get('/')
+ assert response.ok?
+ assert_equal 'Hello from middleware', response.body
+ end
+
+ it 'automatically forwards requests downstream when no matching route found' do
+ response = request.get('/missing')
+ assert_equal 210, response.status
+ assert_equal 'Hello from downstream', response.body
+ end
+
+ it 'calls #route_missing before forwarding downstream' do
+ response = request.get('/missing')
+ assert_equal '1', response['X-Route-Missing']
+ end
+
+ class TestMiddleware < Sinatra::Base
+ get '/low-level-forward' do
+ app.call(env)
+ end
+ end
+
+ it 'can call the downstream app directly and return result' do
+ response = request.get('/low-level-forward')
+ assert_equal 210, response.status
+ assert_equal 'true', response['X-Downstream']
+ assert_equal 'Hello from downstream', response.body
+ end
+
+ class TestMiddleware < Sinatra::Base
+ get '/explicit-forward' do
+ response['X-Middleware'] = 'true'
+ res = forward
+ assert_nil res
+ assert_equal 210, response.status
+ assert_equal 'true', response['X-Downstream']
+ assert_equal ['Hello from downstream'], response.body
+ 'Hello after explicit forward'
+ end
+ end
+
+ it 'forwards the request downstream and integrates the response into the current context' do
+ response = request.get('/explicit-forward')
+ assert_equal 210, response.status
+ assert_equal 'true', response['X-Downstream']
+ assert_equal 'Hello after explicit forward', response.body
+ assert_equal '28', response['Content-Length']
+ end
+
+ app_content_length = lambda {|env|
+ [200, {'Content-Length' => '16'}, 'From downstream!']}
+
+ class TestMiddlewareContentLength < Sinatra::Base
+ get '/forward' do
+ res = forward
+ 'From after explicit forward!'
+ end
+ end
+
+ middleware_content_length = TestMiddlewareContentLength.new(app_content_length)
+ request_content_length = Rack::MockRequest.new(middleware_content_length)
+
+ it "sets content length for last response" do
+ response = request_content_length.get('/forward')
+ assert_equal '28', response['Content-Length']
+ end
+ end
+end
diff --git a/vendor/sinatra/test/builder_test.rb b/vendor/sinatra/test/builder_test.rb
new file mode 100644
index 0000000..04ab3a5
--- /dev/null
+++ b/vendor/sinatra/test/builder_test.rb
@@ -0,0 +1,65 @@
+require File.dirname(__FILE__) + '/helper'
+require 'builder'
+
+class BuilderTest < Test::Unit::TestCase
+ def builder_app(&block)
+ mock_app {
+ set :views, File.dirname(__FILE__) + '/views'
+ get '/', &block
+ }
+ get '/'
+ end
+
+ it 'renders inline Builder strings' do
+ builder_app { builder 'xml.instruct!' }
+ assert ok?
+ assert_equal %{<?xml version="1.0" encoding="UTF-8"?>\n}, body
+ end
+
+ it 'renders inline blocks' do
+ builder_app {
+ @name = "Frank & Mary"
+ builder do |xml|
+ xml.couple @name
+ end
+ }
+ assert ok?
+ assert_equal "<couple>Frank & Mary</couple>\n", body
+ end
+
+ it 'renders .builder files in views path' do
+ builder_app {
+ @name = "Blue"
+ builder :hello
+ }
+ assert ok?
+ assert_equal %(<exclaim>You're my boy, Blue!</exclaim>\n), body
+ end
+
+ it "renders with inline layouts" do
+ mock_app {
+ layout do
+ %(xml.layout { xml << yield })
+ end
+ get('/') { builder %(xml.em 'Hello World') }
+ }
+ get '/'
+ assert ok?
+ assert_equal "<layout>\n<em>Hello World</em>\n</layout>\n", body
+ end
+
+ it "renders with file layouts" do
+ builder_app {
+ builder %(xml.em 'Hello World'), :layout => :layout2
+ }
+ assert ok?
+ assert_equal "<layout>\n<em>Hello World</em>\n</layout>\n", body
+ end
+
+ it "raises error if template not found" do
+ mock_app {
+ get('/') { builder :no_such_template }
+ }
+ assert_raise(Errno::ENOENT) { get('/') }
+ end
+end
diff --git a/vendor/sinatra/test/contest.rb b/vendor/sinatra/test/contest.rb
new file mode 100644
index 0000000..de71601
--- /dev/null
+++ b/vendor/sinatra/test/contest.rb
@@ -0,0 +1,64 @@
+require "test/unit"
+
+# Test::Unit loads a default test if the suite is empty, and the only
+# purpose of that test is to fail. As having empty contexts is a common
+# practice, we decided to overwrite TestSuite#empty? in order to
+# allow them. Having a failure when no tests have been defined seems
+# counter-intuitive.
+class Test::Unit::TestSuite
+ unless method_defined?(:empty?)
+ def empty?
+ false
+ end
+ end
+end
+
+# We added setup, test and context as class methods, and the instance
+# method setup now iterates on the setup blocks. Note that all setup
+# blocks must be defined with the block syntax. Adding a setup instance
+# method defeats the purpose of this library.
+class Test::Unit::TestCase
+ def self.setup(&block)
+ setup_blocks << block
+ end
+
+ def setup
+ self.class.setup_blocks.each do |block|
+ instance_eval(&block)
+ end
+ end
+
+ def self.context(name, &block)
+ subclass = Class.new(self.superclass)
+ subclass.setup_blocks.unshift(*setup_blocks)
+ subclass.class_eval(&block)
+ const_set(context_name(name), subclass)
+ end
+
+ def self.test(name, &block)
+ define_method(test_name(name), &block)
+ end
+
+ class << self
+ alias_method :should, :test
+ alias_method :describe, :context
+ end
+
+private
+
+ def self.setup_blocks
+ @setup_blocks ||= []
+ end
+
+ def self.context_name(name)
+ "Test#{sanitize_name(name).gsub(/(^| )(\w)/) { $2.upcase }}".to_sym
+ end
+
+ def self.test_name(name)
+ "test_#{sanitize_name(name).gsub(/\s+/,'_')}".to_sym
+ end
+
+ def self.sanitize_name(name)
+ name.gsub(/\W+/, ' ').strip
+ end
+end
diff --git a/vendor/sinatra/test/data/reload_app_file.rb b/vendor/sinatra/test/data/reload_app_file.rb
new file mode 100644
index 0000000..673ab7c
--- /dev/null
+++ b/vendor/sinatra/test/data/reload_app_file.rb
@@ -0,0 +1,3 @@
+$reload_count += 1
+
+$reload_app.get('/') { 'Hello from reload file' }
diff --git a/vendor/sinatra/test/erb_test.rb b/vendor/sinatra/test/erb_test.rb
new file mode 100644
index 0000000..cc68c5c
--- /dev/null
+++ b/vendor/sinatra/test/erb_test.rb
@@ -0,0 +1,81 @@
+require File.dirname(__FILE__) + '/helper'
+
+class ERBTest < Test::Unit::TestCase
+ def erb_app(&block)
+ mock_app {
+ set :views, File.dirname(__FILE__) + '/views'
+ get '/', &block
+ }
+ get '/'
+ end
+
+ it 'renders inline ERB strings' do
+ erb_app { erb '<%= 1 + 1 %>' }
+ assert ok?
+ assert_equal '2', body
+ end
+
+ it 'renders .erb files in views path' do
+ erb_app { erb :hello }
+ assert ok?
+ assert_equal "Hello World\n", body
+ end
+
+ it 'takes a :locals option' do
+ erb_app {
+ locals = {:foo => 'Bar'}
+ erb '<%= foo %>', :locals => locals
+ }
+ assert ok?
+ assert_equal 'Bar', body
+ end
+
+ it "renders with inline layouts" do
+ mock_app {
+ layout { 'THIS. IS. <%= yield.upcase %>!' }
+ get('/') { erb 'Sparta' }
+ }
+ get '/'
+ assert ok?
+ assert_equal 'THIS. IS. SPARTA!', body
+ end
+
+ it "renders with file layouts" do
+ erb_app {
+ erb 'Hello World', :layout => :layout2
+ }
+ assert ok?
+ assert_equal "ERB Layout!\nHello World\n", body
+ end
+
+ it "renders erb with blocks" do
+ mock_app {
+ def container
+ @_out_buf << "THIS."
+ yield
+ @_out_buf << "SPARTA!"
+ end
+ def is; "IS." end
+ get '/' do
+ erb '<% container do %> <%= is %> <% end %>'
+ end
+ }
+ get '/'
+ assert ok?
+ assert_equal 'THIS. IS. SPARTA!', body
+ end
+
+ it "can be used in a nested fashion for partials and whatnot" do
+ mock_app {
+ template(:inner) { "<inner><%= 'hi' %></inner>" }
+ template(:outer) { "<outer><%= erb :inner %></outer>" }
+ get '/' do
+ erb :outer
+ end
+ }
+
+ get '/'
+ assert ok?
+ assert_equal '<outer><inner>hi</inner></outer>', body
+ end
+end
diff --git a/vendor/sinatra/test/extensions_test.rb b/vendor/sinatra/test/extensions_test.rb
new file mode 100644
index 0000000..7977c29
--- /dev/null
+++ b/vendor/sinatra/test/extensions_test.rb
@@ -0,0 +1,100 @@
+require File.dirname(__FILE__) + '/helper'
+
+class ExtensionsTest < Test::Unit::TestCase
+ module FooExtensions
+ def foo
+ end
+
+ private
+ def im_hiding_in_ur_foos
+ end
+ end
+
+ module BarExtensions
+ def bar
+ end
+ end
+
+ module BazExtensions
+ def baz
+ end
+ end
+
+ module QuuxExtensions
+ def quux
+ end
+ end
+
+ module PainExtensions
+ def foo=(name); end
+ def bar?(name); end
+ def fizz!(name); end
+ end
+
+ it 'will add the methods to the DSL for the class in which you register them and its subclasses' do
+ Sinatra::Base.register FooExtensions
+ assert Sinatra::Base.respond_to?(:foo)
+
+ Sinatra::Default.register BarExtensions
+ assert Sinatra::Default.respond_to?(:bar)
+ assert Sinatra::Default.respond_to?(:foo)
+ assert !Sinatra::Base.respond_to?(:bar)
+ end
+
+ it 'allows extending by passing a block' do
+ Sinatra::Base.register {
+ def im_in_ur_anonymous_module; end
+ }
+ assert Sinatra::Base.respond_to?(:im_in_ur_anonymous_module)
+ end
+
+ it 'will make sure any public methods added via Default#register are delegated to Sinatra::Delegator' do
+ Sinatra::Default.register FooExtensions
+ assert Sinatra::Delegator.private_instance_methods.
+ map { |m| m.to_sym }.include?(:foo)
+ assert !Sinatra::Delegator.private_instance_methods.
+ map { |m| m.to_sym }.include?(:im_hiding_in_ur_foos)
+ end
+
+ it 'will handle special method names' do
+ Sinatra::Default.register PainExtensions
+ assert Sinatra::Delegator.private_instance_methods.
+ map { |m| m.to_sym }.include?(:foo=)
+ assert Sinatra::Delegator.private_instance_methods.
+ map { |m| m.to_sym }.include?(:bar?)
+ assert Sinatra::Delegator.private_instance_methods.
+ map { |m| m.to_sym }.include?(:fizz!)
+ end
+
+ it 'will not delegate methods on Base#register' do
+ Sinatra::Base.register QuuxExtensions
+ assert !Sinatra::Delegator.private_instance_methods.include?("quux")
+ end
+
+ it 'will extend the Sinatra::Default application by default' do
+ Sinatra.register BazExtensions
+ assert !Sinatra::Base.respond_to?(:baz)
+ assert Sinatra::Default.respond_to?(:baz)
+ end
+
+ module BizzleExtension
+ def bizzle
+ bizzle_option
+ end
+
+ def self.registered(base)
+ fail "base should be BizzleApp" unless base == BizzleApp
+ fail "base should have already extended BizzleExtension" unless base.respond_to?(:bizzle)
+ base.set :bizzle_option, 'bizzle!'
+ end
+ end
+
+ class BizzleApp < Sinatra::Base
+ end
+
+ it 'sends .registered to the extension module after extending the class' do
+ BizzleApp.register BizzleExtension
+ assert_equal 'bizzle!', BizzleApp.bizzle_option
+ assert_equal 'bizzle!', BizzleApp.bizzle
+ end
+end
diff --git a/vendor/sinatra/test/filter_test.rb b/vendor/sinatra/test/filter_test.rb
new file mode 100644
index 0000000..dc13f58
--- /dev/null
+++ b/vendor/sinatra/test/filter_test.rb
@@ -0,0 +1,111 @@
+require File.dirname(__FILE__) + '/helper'
+
+class FilterTest < Test::Unit::TestCase
+ it "executes filters in the order defined" do
+ count = 0
+ mock_app do
+ get('/') { 'Hello World' }
+ before {
+ assert_equal 0, count
+ count = 1
+ }
+ before {
+ assert_equal 1, count
+ count = 2
+ }
+ end
+
+ get '/'
+ assert ok?
+ assert_equal 2, count
+ assert_equal 'Hello World', body
+ end
+
+ it "allows filters to modify the request" do
+ mock_app {
+ get('/foo') { 'foo' }
+ get('/bar') { 'bar' }
+ before { request.path_info = '/bar' }
+ }
+
+ get '/foo'
+ assert ok?
+ assert_equal 'bar', body
+ end
+
+ it "can modify instance variables available to routes" do
+ mock_app {
+ before { @foo = 'bar' }
+ get('/foo') { @foo }
+ }
+
+ get '/foo'
+ assert ok?
+ assert_equal 'bar', body
+ end
+
+ it "allows redirects in filters" do
+ mock_app {
+ before { redirect '/bar' }
+ get('/foo') do
+ fail 'before block should have halted processing'
+ 'ORLY?!'
+ end
+ }
+
+ get '/foo'
+ assert redirect?
+ assert_equal '/bar', response['Location']
+ assert_equal '', body
+ end
+
+ it "does not modify the response with its return value" do
+ mock_app {
+ before { 'Hello World!' }
+ get '/foo' do
+ assert_equal [], response.body
+ 'cool'
+ end
+ }
+
+ get '/foo'
+ assert ok?
+ assert_equal 'cool', body
+ end
+
+ it "does modify the response with halt" do
+ mock_app {
+ before { halt 302, 'Hi' }
+ get '/foo' do
+ "should not happen"
+ end
+ }
+
+ get '/foo'
+ assert_equal 302, response.status
+ assert_equal 'Hi', body
+ end
+
+ it "gives you access to params" do
+ mock_app {
+ before { @foo = params['foo'] }
+ get('/foo') { @foo }
+ }
+
+ get '/foo?foo=cool'
+ assert ok?
+ assert_equal 'cool', body
+ end
+
+ it "runs filters defined in superclasses" do
+ base = Class.new(Sinatra::Base)
+ base.before { @foo = 'hello from superclass' }
+
+ mock_app(base) {
+ get('/foo') { @foo }
+ }
+
+ get '/foo'
+ assert_equal 'hello from superclass', body
+ end
+end
diff --git a/vendor/sinatra/test/haml_test.rb b/vendor/sinatra/test/haml_test.rb
new file mode 100644
index 0000000..3d6ed69
--- /dev/null
+++ b/vendor/sinatra/test/haml_test.rb
@@ -0,0 +1,90 @@
+require File.dirname(__FILE__) + '/helper'
+require 'haml'
+
+class HAMLTest < Test::Unit::TestCase
+ def haml_app(&block)
+ mock_app {
+ set :views, File.dirname(__FILE__) + '/views'
+ get '/', &block
+ }
+ get '/'
+ end
+
+ it 'renders inline HAML strings' do
+ haml_app { haml '%h1 Hiya' }
+ assert ok?
+ assert_equal "<h1>Hiya</h1>\n", body
+ end
+
+ it 'renders .haml files in views path' do
+ haml_app { haml :hello }
+ assert ok?
+ assert_equal "<h1>Hello From Haml</h1>\n", body
+ end
+
+ it "renders with inline layouts" do
+ mock_app {
+ layout { %q(%h1= 'THIS. IS. ' + yield.upcase) }
+ get('/') { haml '%em Sparta' }
+ }
+ get '/'
+ assert ok?
+ assert_equal "<h1>THIS. IS. <EM>SPARTA</EM></h1>\n", body
+ end
+
+ it "renders with file layouts" do
+ haml_app {
+ haml 'Hello World', :layout => :layout2
+ }
+ assert ok?
+ assert_equal "<h1>HAML Layout!</h1>\n<p>Hello World</p>\n", body
+ end
+
+ it "raises error if template not found" do
+ mock_app {
+ get('/') { haml :no_such_template }
+ }
+ assert_raise(Errno::ENOENT) { get('/') }
+ end
+
+ it "passes HAML options to the Haml engine" do
+ mock_app {
+ get '/' do
+ haml "!!!\n%h1 Hello World", :format => :html5
+ end
+ }
+ get '/'
+ assert ok?
+ assert_equal "<!DOCTYPE html>\n<h1>Hello World</h1>\n", body
+ end
+
+ it "passes default HAML options to the Haml engine" do
+ mock_app {
+ set :haml, {:format => :html5}
+ get '/' do
+ haml "!!!\n%h1 Hello World"
+ end
+ }
+ get '/'
+ assert ok?
+ assert_equal "<!DOCTYPE html>\n<h1>Hello World</h1>\n", body
+ end
+
+ it "merges the default HAML options with the overrides and passes them to the Haml engine" do
+ mock_app {
+ set :haml, {:format => :html5, :attr_wrapper => '"'} # default HAML attr are <tag attr='single-quoted'>
+ get '/' do
+ haml "!!!\n%h1{:class => :header} Hello World"
+ end
+ get '/html4' do
+ haml "!!!\n%h1{:class => 'header'} Hello World", :format => :html4
+ end
+ }
+ get '/'
+ assert ok?
+ assert_equal "<!DOCTYPE html>\n<h1 class=\"header\">Hello World</h1>\n", body
+ get '/html4'
+ assert ok?
+ assert_match(/^<!DOCTYPE html PUBLIC (.*) HTML 4.01/, body)
+ end
+end
diff --git a/vendor/sinatra/test/helper.rb b/vendor/sinatra/test/helper.rb
new file mode 100644
index 0000000..7069929
--- /dev/null
+++ b/vendor/sinatra/test/helper.rb
@@ -0,0 +1,76 @@
+ENV['RACK_ENV'] = 'test'
+
+begin
+ require 'rack'
+rescue LoadError
+ require 'rubygems'
+ require 'rack'
+end
+
+testdir = File.dirname(__FILE__)
+$LOAD_PATH.unshift testdir unless $LOAD_PATH.include?(testdir)
+
+libdir = File.dirname(File.dirname(__FILE__)) + '/lib'
+$LOAD_PATH.unshift libdir unless $LOAD_PATH.include?(libdir)
+
+require 'contest'
+require 'rack/test'
+require 'sinatra/base'
+
+class Sinatra::Base
+ # Allow assertions in request context
+ include Test::Unit::Assertions
+end
+
+Sinatra::Base.set :environment, :test
+
+class Test::Unit::TestCase
+ include Rack::Test::Methods
+
+ class << self
+ alias_method :it, :test
+ end
+
+ alias_method :response, :last_response
+
+ setup do
+ Sinatra::Base.set :environment, :test
+ end
+
+ # Sets up a Sinatra::Base subclass defined with the block
+ # given. Used in setup or individual spec methods to establish
+ # the application.
+ def mock_app(base=Sinatra::Base, &block)
+ @app = Sinatra.new(base, &block)
+ end
+
+ def app
+ Rack::Lint.new(@app)
+ end
+
+ def body
+ response.body.to_s
+ end
+
+ # Delegate other missing methods to response.
+ def method_missing(name, *args, &block)
+ if response && response.respond_to?(name)
+ response.send(name, *args, &block)
+ else
+ super
+ end
+ end
+
+ # Also check response since we delegate there.
+ def respond_to?(symbol, include_private=false)
+ super || (response && response.respond_to?(symbol, include_private))
+ end
+
+ # Do not output warnings for the duration of the block.
+ def silence_warnings
+ $VERBOSE, v = nil, $VERBOSE
+ yield
+ ensure
+ $VERBOSE = v
+ end
+end
diff --git a/vendor/sinatra/test/helpers_test.rb b/vendor/sinatra/test/helpers_test.rb
new file mode 100644
index 0000000..673aff1
--- /dev/null
+++ b/vendor/sinatra/test/helpers_test.rb
@@ -0,0 +1,503 @@
+require File.dirname(__FILE__) + '/helper'
+
+class HelpersTest < Test::Unit::TestCase
+ def test_default
+ assert true
+ end
+
+ describe 'status' do
+ setup do
+ mock_app {
+ get '/' do
+ status 207
+ nil
+ end
+ }
+ end
+
+ it 'sets the response status code' do
+ get '/'
+ assert_equal 207, response.status
+ end
+ end
+
+ describe 'body' do
+ it 'takes a block for defered body generation' do
+ mock_app {
+ get '/' do
+ body { 'Hello World' }
+ end
+ }
+
+ get '/'
+ assert_equal 'Hello World', body
+ end
+
+ it 'takes a String, Array, or other object responding to #each' do
+ mock_app {
+ get '/' do
+ body 'Hello World'
+ end
+ }
+
+ get '/'
+ assert_equal 'Hello World', body
+ end
+ end
+
+ describe 'redirect' do
+ it 'uses a 302 when only a path is given' do
+ mock_app {
+ get '/' do
+ redirect '/foo'
+ fail 'redirect should halt'
+ end
+ }
+
+ get '/'
+ assert_equal 302, status
+ assert_equal '', body
+ assert_equal '/foo', response['Location']
+ end
+
+ it 'uses the code given when specified' do
+ mock_app {
+ get '/' do
+ redirect '/foo', 301
+ fail 'redirect should halt'
+ end
+ }
+
+ get '/'
+ assert_equal 301, status
+ assert_equal '', body
+ assert_equal '/foo', response['Location']
+ end
+
+ it 'redirects back to request.referer when passed back' do
+ mock_app {
+ get '/try_redirect' do
+ redirect back
+ end
+ }
+
+ request = Rack::MockRequest.new(@app)
+ response = request.get('/try_redirect', 'HTTP_REFERER' => '/foo')
+ assert_equal 302, response.status
+ assert_equal '/foo', response['Location']
+ end
+ end
+
+ describe 'error' do
+ it 'sets a status code and halts' do
+ mock_app {
+ get '/' do
+ error 501
+ fail 'error should halt'
+ end
+ }
+
+ get '/'
+ assert_equal 501, status
+ assert_equal '', body
+ end
+
+ it 'takes an optional body' do
+ mock_app {
+ get '/' do
+ error 501, 'FAIL'
+ fail 'error should halt'
+ end
+ }
+
+ get '/'
+ assert_equal 501, status
+ assert_equal 'FAIL', body
+ end
+
+ it 'uses a 500 status code when first argument is a body' do
+ mock_app {
+ get '/' do
+ error 'FAIL'
+ fail 'error should halt'
+ end
+ }
+
+ get '/'
+ assert_equal 500, status
+ assert_equal 'FAIL', body
+ end
+ end
+
+ describe 'not_found' do
+ it 'halts with a 404 status' do
+ mock_app {
+ get '/' do
+ not_found
+ fail 'not_found should halt'
+ end
+ }
+
+ get '/'
+ assert_equal 404, status
+ assert_equal '', body
+ end
+ end
+
+ describe 'headers' do
+ it 'sets headers on the response object when given a Hash' do
+ mock_app {
+ get '/' do
+ headers 'X-Foo' => 'bar', 'X-Baz' => 'bling'
+ 'kthx'
+ end
+ }
+
+ get '/'
+ assert ok?
+ assert_equal 'bar', response['X-Foo']
+ assert_equal 'bling', response['X-Baz']
+ assert_equal 'kthx', body
+ end
+
+ it 'returns the response headers hash when no hash provided' do
+ mock_app {
+ get '/' do
+ headers['X-Foo'] = 'bar'
+ 'kthx'
+ end
+ }
+
+ get '/'
+ assert ok?
+ assert_equal 'bar', response['X-Foo']
+ end
+ end
+
+ describe 'session' do
+ it 'uses the existing rack.session' do
+ mock_app {
+ get '/' do
+ session[:foo]
+ end
+ }
+
+ get '/', {}, { 'rack.session' => { :foo => 'bar' } }
+ assert_equal 'bar', body
+ end
+
+ it 'creates a new session when none provided' do
+ mock_app {
+ get '/' do
+ assert session.empty?
+ session[:foo] = 'bar'
+ 'Hi'
+ end
+ }
+
+ get '/'
+ assert_equal 'Hi', body
+ end
+ end
+
+ describe 'media_type' do
+ include Sinatra::Helpers
+
+ it "looks up media types in Rack's MIME registry" do
+ Rack::Mime::MIME_TYPES['.foo'] = 'application/foo'
+ assert_equal 'application/foo', media_type('foo')
+ assert_equal 'application/foo', media_type('.foo')
+ assert_equal 'application/foo', media_type(:foo)
+ end
+
+ it 'returns nil when given nil' do
+ assert media_type(nil).nil?
+ end
+
+ it 'returns nil when media type not registered' do
+ assert media_type(:bizzle).nil?
+ end
+
+ it 'returns the argument when given a media type string' do
+ assert_equal 'text/plain', media_type('text/plain')
+ end
+ end
+
+ describe 'content_type' do
+ it 'sets the Content-Type header' do
+ mock_app {
+ get '/' do
+ content_type 'text/plain'
+ 'Hello World'
+ end
+ }
+
+ get '/'
+ assert_equal 'text/plain', response['Content-Type']
+ assert_equal 'Hello World', body
+ end
+
+ it 'takes media type parameters (like charset=)' do
+ mock_app {
+ get '/' do
+ content_type 'text/html', :charset => 'utf-8'
+ "<h1>Hello, World</h1>"
+ end
+ }
+
+ get '/'
+ assert ok?
+ assert_equal 'text/html;charset=utf-8', response['Content-Type']
+ assert_equal "<h1>Hello, World</h1>", body
+ end
+
+ it "looks up symbols in Rack's mime types dictionary" do
+ Rack::Mime::MIME_TYPES['.foo'] = 'application/foo'
+ mock_app {
+ get '/foo.xml' do
+ content_type :foo
+ "I AM FOO"
+ end
+ }
+
+ get '/foo.xml'
+ assert ok?
+ assert_equal 'application/foo', response['Content-Type']
+ assert_equal 'I AM FOO', body
+ end
+
+ it 'fails when no mime type is registered for the argument provided' do
+ mock_app {
+ get '/foo.xml' do
+ content_type :bizzle
+ "I AM FOO"
+ end
+ }
+
+ assert_raise(RuntimeError) { get '/foo.xml' }
+ end
+ end
+
+ describe 'send_file' do
+ setup do
+ @file = File.dirname(__FILE__) + '/file.txt'
+ File.open(@file, 'wb') { |io| io.write('Hello World') }
+ end
+
+ def teardown
+ File.unlink @file
+ @file = nil
+ end
+
+ def send_file_app(opts={})
+ path = @file
+ mock_app {
+ get '/file.txt' do
+ send_file path, opts
+ end
+ }
+ end
+
+ it "sends the contents of the file" do
+ send_file_app
+ get '/file.txt'
+ assert ok?
+ assert_equal 'Hello World', body
+ end
+
+ it 'sets the Content-Type response header if a mime-type can be located' do
+ send_file_app
+ get '/file.txt'
+ assert_equal 'text/plain', response['Content-Type']
+ end
+
+ it 'sets the Content-Length response header' do
+ send_file_app
+ get '/file.txt'
+ assert_equal 'Hello World'.length.to_s, response['Content-Length']
+ end
+
+ it 'sets the Last-Modified response header' do
+ send_file_app
+ get '/file.txt'
+ assert_equal File.mtime(@file).httpdate, response['Last-Modified']
+ end
+
+ it "returns a 404 when not found" do
+ mock_app {
+ get '/' do
+ send_file 'this-file-does-not-exist.txt'
+ end
+ }
+ get '/'
+ assert not_found?
+ end
+
+ it "does not set the Content-Disposition header by default" do
+ send_file_app
+ get '/file.txt'
+ assert_nil response['Content-Disposition']
+ end
+
+ it "sets the Content-Disposition header when :disposition set to 'attachment'" do
+ send_file_app :disposition => 'attachment'
+ get '/file.txt'
+ assert_equal 'attachment; filename="file.txt"', response['Content-Disposition']
+ end
+
+ it "sets the Content-Disposition header when :filename provided" do
+ send_file_app :filename => 'foo.txt'
+ get '/file.txt'
+ assert_equal 'attachment; filename="foo.txt"', response['Content-Disposition']
+ end
+ end
+
+ describe 'last_modified' do
+ setup do
+ now = Time.now
+ mock_app {
+ get '/' do
+ body { 'Hello World' }
+ last_modified now
+ 'Boo!'
+ end
+ }
+ @now = now
+ end
+
+ it 'sets the Last-Modified header to a valid RFC 2616 date value' do
+ get '/'
+ assert_equal @now.httpdate, response['Last-Modified']
+ end
+
+ it 'returns a body when conditional get misses' do
+ get '/'
+ assert_equal 200, status
+ assert_equal 'Boo!', body
+ end
+
+ it 'halts when a conditional GET matches' do
+ get '/', {}, { 'HTTP_IF_MODIFIED_SINCE' => @now.httpdate }
+ assert_equal 304, status
+ assert_equal '', body
+ end
+ end
+
+ describe 'etag' do
+ setup do
+ mock_app {
+ get '/' do
+ body { 'Hello World' }
+ etag 'FOO'
+ 'Boo!'
+ end
+ }
+ end
+
+ it 'sets the ETag header' do
+ get '/'
+ assert_equal '"FOO"', response['ETag']
+ end
+
+ it 'returns a body when conditional get misses' do
+ get '/'
+ assert_equal 200, status
+ assert_equal 'Boo!', body
+ end
+
+ it 'halts when a conditional GET matches' do
+ get '/', {}, { 'HTTP_IF_NONE_MATCH' => '"FOO"' }
+ assert_equal 304, status
+ assert_equal '', body
+ end
+
+ it 'should handle multiple ETag values in If-None-Match header' do
+ get '/', {}, { 'HTTP_IF_NONE_MATCH' => '"BAR", *' }
+ assert_equal 304, status
+ assert_equal '', body
+ end
+
+ it 'uses a weak etag with the :weak option' do
+ mock_app {
+ get '/' do
+ etag 'FOO', :weak
+ "that's weak, dude."
+ end
+ }
+ get '/'
+ assert_equal 'W/"FOO"', response['ETag']
+ end
+ end
+
+ describe 'back' do
+ it "makes redirecting back pretty" do
+ mock_app {
+ get '/foo' do
+ redirect back
+ end
+ }
+
+ get '/foo', {}, 'HTTP_REFERER' => 'http://github.com'
+ assert redirect?
+ assert_equal "http://github.com", response.location
+ end
+ end
+
+ module ::HelperOne; def one; '1'; end; end
+ module ::HelperTwo; def two; '2'; end; end
+
+ describe 'Adding new helpers' do
+ it 'takes a list of modules to mix into the app' do
+ mock_app {
+ helpers ::HelperOne, ::HelperTwo
+
+ get '/one' do
+ one
+ end
+
+ get '/two' do
+ two
+ end
+ }
+
+ get '/one'
+ assert_equal '1', body
+
+ get '/two'
+ assert_equal '2', body
+ end
+
+ it 'takes a block to mix into the app' do
+ mock_app {
+ helpers do
+ def foo
+ 'foo'
+ end
+ end
+
+ get '/' do
+ foo
+ end
+ }
+
+ get '/'
+ assert_equal 'foo', body
+ end
+
+ it 'evaluates the block in class context so that methods can be aliased' do
+ mock_app {
+ helpers do
+ alias_method :h, :escape_html
+ end
+
+ get '/' do
+ h('42 < 43')
+ end
+ }
+
+ get '/'
+ assert ok?
+ assert_equal '42 < 43', body
+ end
+ end
+end
diff --git a/vendor/sinatra/test/mapped_error_test.rb b/vendor/sinatra/test/mapped_error_test.rb
new file mode 100644
index 0000000..337de3f
--- /dev/null
+++ b/vendor/sinatra/test/mapped_error_test.rb
@@ -0,0 +1,186 @@
+require File.dirname(__FILE__) + '/helper'
+
+class FooError < RuntimeError
+end
+
+class FooNotFound < Sinatra::NotFound
+end
+
+class MappedErrorTest < Test::Unit::TestCase
+ def test_default
+ assert true
+ end
+
+ describe 'Exception Mappings' do
+ it 'invokes handlers registered with ::error when raised' do
+ mock_app {
+ set :raise_errors, false
+ error(FooError) { 'Foo!' }
+ get '/' do
+ raise FooError
+ end
+ }
+ get '/'
+ assert_equal 500, status
+ assert_equal 'Foo!', body
+ end
+
+ it 'uses the Exception handler if no matching handler found' do
+ mock_app {
+ set :raise_errors, false
+ error(Exception) { 'Exception!' }
+ get '/' do
+ raise FooError
+ end
+ }
+
+ get '/'
+ assert_equal 500, status
+ assert_equal 'Exception!', body
+ end
+
+ it "sets env['sinatra.error'] to the rescued exception" do
+ mock_app {
+ set :raise_errors, false
+ error(FooError) {
+ assert env.include?('sinatra.error')
+ assert env['sinatra.error'].kind_of?(FooError)
+ 'looks good'
+ }
+ get '/' do
+ raise FooError
+ end
+ }
+ get '/'
+ assert_equal 'looks good', body
+ end
+
+ it "raises without calling the handler when the raise_errors options is set" do
+ mock_app {
+ set :raise_errors, true
+ error(FooError) { "she's not there." }
+ get '/' do
+ raise FooError
+ end
+ }
+ assert_raise(FooError) { get '/' }
+ end
+
+ it "never raises Sinatra::NotFound beyond the application" do
+ mock_app {
+ set :raise_errors, true
+ get '/' do
+ raise Sinatra::NotFound
+ end
+ }
+ assert_nothing_raised { get '/' }
+ assert_equal 404, status
+ end
+
+ it "cascades for subclasses of Sinatra::NotFound" do
+ mock_app {
+ set :raise_errors, true
+ error(FooNotFound) { "foo! not found." }
+ get '/' do
+ raise FooNotFound
+ end
+ }
+ assert_nothing_raised { get '/' }
+ assert_equal 404, status
+ assert_equal 'foo! not found.', body
+ end
+
+ it 'has a not_found method for backwards compatibility' do
+ mock_app {
+ not_found do
+ "Lost, are we?"
+ end
+ }
+
+ get '/test'
+ assert_equal 404, status
+ assert_equal "Lost, are we?", body
+ end
+
+ it 'inherits error mappings from base class' do
+ base = Class.new(Sinatra::Base)
+ base.error(FooError) { 'base class' }
+
+ mock_app(base) {
+ set :raise_errors, false
+ get '/' do
+ raise FooError
+ end
+ }
+
+ get '/'
+ assert_equal 'base class', body
+ end
+
+ it 'overrides error mappings in base class' do
+ base = Class.new(Sinatra::Base)
+ base.error(FooError) { 'base class' }
+
+ mock_app(base) {
+ set :raise_errors, false
+ error(FooError) { 'subclass' }
+ get '/' do
+ raise FooError
+ end
+ }
+
+ get '/'
+ assert_equal 'subclass', body
+ end
+ end
+
+ describe 'Custom Error Pages' do
+ it 'allows numeric status code mappings to be registered with ::error' do
+ mock_app {
+ set :raise_errors, false
+ error(500) { 'Foo!' }
+ get '/' do
+ [500, {}, 'Internal Foo Error']
+ end
+ }
+ get '/'
+ assert_equal 500, status
+ assert_equal 'Foo!', body
+ end
+
+ it 'allows ranges of status code mappings to be registered with :error' do
+ mock_app {
+ set :raise_errors, false
+ error(500..550) { "Error: #{response.status}" }
+ get '/' do
+ [507, {}, 'A very special error']
+ end
+ }
+ get '/'
+ assert_equal 507, status
+ assert_equal 'Error: 507', body
+ end
+
+ class FooError < RuntimeError
+ end
+
+ it 'runs after exception mappings and overwrites body' do
+ mock_app {
+ set :raise_errors, false
+ error FooError do
+ response.status = 502
+ 'from exception mapping'
+ end
+ error(500) { 'from 500 handler' }
+ error(502) { 'from custom error page' }
+
+ get '/' do
+ raise FooError
+ end
+ }
+ get '/'
+ assert_equal 502, status
+ assert_equal 'from custom error page', body
+ end
+ end
+end
diff --git a/vendor/sinatra/test/middleware_test.rb b/vendor/sinatra/test/middleware_test.rb
new file mode 100644
index 0000000..2ebef29
--- /dev/null
+++ b/vendor/sinatra/test/middleware_test.rb
@@ -0,0 +1,68 @@
+require File.dirname(__FILE__) + '/helper'
+
+class MiddlewareTest < Test::Unit::TestCase
+ setup do
+ @app = mock_app(Sinatra::Default) {
+ get '/*' do
+ response.headers['X-Tests'] = env['test.ran'].
+ map { |n| n.split('::').last }.
+ join(', ')
+ env['PATH_INFO']
+ end
+ }
+ end
+
+ class MockMiddleware < Struct.new(:app)
+ def call(env)
+ (env['test.ran'] ||= []) << self.class.to_s
+ app.call(env)
+ end
+ end
+
+ class UpcaseMiddleware < MockMiddleware
+ def call(env)
+ env['PATH_INFO'] = env['PATH_INFO'].upcase
+ super
+ end
+ end
+
+ it "is added with Sinatra::Application.use" do
+ @app.use UpcaseMiddleware
+ get '/hello-world'
+ assert ok?
+ assert_equal '/HELLO-WORLD', body
+ end
+
+ class DowncaseMiddleware < MockMiddleware
+ def call(env)
+ env['PATH_INFO'] = env['PATH_INFO'].downcase
+ super
+ end
+ end
+
+ it "runs in the order defined" do
+ @app.use UpcaseMiddleware
+ @app.use DowncaseMiddleware
+ get '/Foo'
+ assert_equal "/foo", body
+ assert_equal "UpcaseMiddleware, DowncaseMiddleware", response['X-Tests']
+ end
+
+ it "resets the prebuilt pipeline when new middleware is added" do
+ @app.use UpcaseMiddleware
+ get '/Foo'
+ assert_equal "/FOO", body
+ @app.use DowncaseMiddleware
+ get '/Foo'
+ assert_equal '/foo', body
+ assert_equal "UpcaseMiddleware, DowncaseMiddleware", response['X-Tests']
+ end
+
+ it "works when app is used as middleware" do
+ @app.use UpcaseMiddleware
+ @app = @app.new
+ get '/Foo'
+ assert_equal "/FOO", body
+ assert_equal "UpcaseMiddleware", response['X-Tests']
+ end
+end
diff --git a/vendor/sinatra/test/options_test.rb b/vendor/sinatra/test/options_test.rb
new file mode 100644
index 0000000..19f5ea2
--- /dev/null
+++ b/vendor/sinatra/test/options_test.rb
@@ -0,0 +1,372 @@
+require File.dirname(__FILE__) + '/helper'
+
+class OptionsTest < Test::Unit::TestCase
+ setup do
+ @base = Sinatra.new(Sinatra::Base)
+ @default = Sinatra.new(Sinatra::Default)
+ @base.set :environment, :development
+ @default.set :environment, :development
+ end
+
+ it 'sets options to literal values' do
+ @base.set(:foo, 'bar')
+ assert @base.respond_to?(:foo)
+ assert_equal 'bar', @base.foo
+ end
+
+ it 'sets options to Procs' do
+ @base.set(:foo, Proc.new { 'baz' })
+ assert @base.respond_to?(:foo)
+ assert_equal 'baz', @base.foo
+ end
+
+ it "sets multiple options with a Hash" do
+ @base.set :foo => 1234,
+ :bar => 'Hello World',
+ :baz => Proc.new { 'bizzle' }
+ assert_equal 1234, @base.foo
+ assert_equal 'Hello World', @base.bar
+ assert_equal 'bizzle', @base.baz
+ end
+
+ it 'inherits option methods when subclassed' do
+ @base.set :foo, 'bar'
+ @base.set :biz, Proc.new { 'baz' }
+
+ sub = Class.new(@base)
+ assert sub.respond_to?(:foo)
+ assert_equal 'bar', sub.foo
+ assert sub.respond_to?(:biz)
+ assert_equal 'baz', sub.biz
+ end
+
+ it 'overrides options in subclass' do
+ @base.set :foo, 'bar'
+ @base.set :biz, Proc.new { 'baz' }
+ sub = Class.new(@base)
+ sub.set :foo, 'bling'
+ assert_equal 'bling', sub.foo
+ assert_equal 'bar', @base.foo
+ end
+
+ it 'creates setter methods when first defined' do
+ @base.set :foo, 'bar'
+ assert @base.respond_to?('foo=')
+ @base.foo = 'biz'
+ assert_equal 'biz', @base.foo
+ end
+
+ it 'creates predicate methods when first defined' do
+ @base.set :foo, 'hello world'
+ assert @base.respond_to?(:foo?)
+ assert @base.foo?
+ @base.set :foo, nil
+ assert !@base.foo?
+ end
+
+ it 'uses existing setter methods if detected' do
+ class << @base
+ def foo
+ @foo
+ end
+ def foo=(value)
+ @foo = 'oops'
+ end
+ end
+
+ @base.set :foo, 'bam'
+ assert_equal 'oops', @base.foo
+ end
+
+ it "sets multiple options to true with #enable" do
+ @base.enable :sessions, :foo, :bar
+ assert @base.sessions
+ assert @base.foo
+ assert @base.bar
+ end
+
+ it "sets multiple options to false with #disable" do
+ @base.disable :sessions, :foo, :bar
+ assert !@base.sessions
+ assert !@base.foo
+ assert !@base.bar
+ end
+
+ it 'enables MethodOverride middleware when :methodoverride is enabled' do
+ @base.set :methodoverride, true
+ @base.put('/') { 'okay' }
+ @app = @base
+ post '/', {'_method'=>'PUT'}, {}
+ assert_equal 200, status
+ assert_equal 'okay', body
+ end
+
+ describe 'clean_trace' do
+ def clean_backtrace(trace)
+ Sinatra::Base.new.send(:clean_backtrace, trace)
+ end
+
+ it 'is enabled on Base' do
+ assert @base.clean_trace?
+ end
+
+ it 'is enabled on Default' do
+ assert @default.clean_trace?
+ end
+
+ it 'does nothing when disabled' do
+ backtrace = [
+ "./lib/sinatra/base.rb",
+ "./myapp:42",
+ ("#{Gem.dir}/some/lib.rb" if defined?(Gem))
+ ].compact
+
+ klass = Class.new(Sinatra::Base)
+ klass.disable :clean_trace
+
+ assert_equal backtrace, klass.new.send(:clean_backtrace, backtrace)
+ end
+
+ it 'removes sinatra lib paths from backtrace when enabled' do
+ backtrace = [
+ "./lib/sinatra/base.rb",
+ "./lib/sinatra/compat.rb:42",
+ "./lib/sinatra/main.rb:55 in `foo'"
+ ]
+ assert clean_backtrace(backtrace).empty?
+ end
+
+ it 'removes ./ prefix from backtrace paths when enabled' do
+ assert_equal ['myapp.rb:42'], clean_backtrace(['./myapp.rb:42'])
+ end
+
+ if defined?(Gem)
+ it 'removes gem lib paths from backtrace when enabled' do
+ assert clean_backtrace(["#{Gem.dir}/some/lib"]).empty?
+ end
+ end
+ end
+
+ describe 'run' do
+ it 'is disabled on Base' do
+ assert ! @base.run?
+ end
+
+ it 'is enabled on Default when not in test environment' do
+ @default.set :environment, :development
+ assert @default.development?
+ assert @default.run?
+
+ @default.set :environment, :development
+ assert @default.run?
+ end
+
+ # TODO: it 'is enabled when $0 == app_file'
+ end
+
+ describe 'raise_errors' do
+ it 'is enabled on Base' do
+ assert @base.raise_errors?
+ end
+
+ it 'is enabled on Default only in test' do
+ @default.set(:environment, :development)
+ assert @default.development?
+ assert ! @default.raise_errors?
+
+ @default.set(:environment, :production)
+ assert ! @default.raise_errors?
+
+ @default.set(:environment, :test)
+ assert @default.raise_errors?
+ end
+ end
+
+ describe 'show_exceptions' do
+ %w[development test production none].each do |environment|
+ it "is disabled on Base in #{environment} environments" do
+ @base.set(:environment, environment)
+ assert ! @base.show_exceptions?
+ end
+ end
+
+ it 'is enabled on Default only in development' do
+ @base.set(:environment, :development)
+ assert @default.development?
+ assert @default.show_exceptions?
+
+ @default.set(:environment, :test)
+ assert ! @default.show_exceptions?
+
+ @base.set(:environment, :production)
+ assert ! @base.show_exceptions?
+ end
+
+ it 'returns a friendly 500' do
+ klass = Sinatra.new(Sinatra::Default)
+ mock_app(klass) {
+ enable :show_exceptions
+
+ get '/' do
+ raise StandardError
+ end
+ }
+
+ get '/'
+ assert_equal 500, status
+ assert body.include?("StandardError")
+ assert body.include?("<code>show_exceptions</code> option")
+ end
+ end
+
+ describe 'dump_errors' do
+ it 'is disabled on Base' do
+ assert ! @base.dump_errors?
+ end
+
+ it 'is enabled on Default' do
+ assert @default.dump_errors?
+ end
+
+ it 'dumps exception with backtrace to rack.errors' do
+ klass = Sinatra.new(Sinatra::Default)
+
+ mock_app(klass) {
+ disable :raise_errors
+
+ error do
+ error = @env['rack.errors'].instance_variable_get(:@error)
+ error.rewind
+
+ error.read
+ end
+
+ get '/' do
+ raise
+ end
+ }
+
+ get '/'
+ assert body.include?("RuntimeError") && body.include?("options_test.rb")
+ end
+ end
+
+ describe 'sessions' do
+ it 'is disabled on Base' do
+ assert ! @base.sessions?
+ end
+
+ it 'is disabled on Default' do
+ assert ! @default.sessions?
+ end
+
+ # TODO: it 'uses Rack::Session::Cookie when enabled' do
+ end
+
+ describe 'logging' do
+ it 'is disabled on Base' do
+ assert ! @base.logging?
+ end
+
+ it 'is enabled on Default when not in test environment' do
+ assert @default.logging?
+
+ @default.set :environment, :test
+ assert ! @default.logging
+ end
+
+ # TODO: it 'uses Rack::CommonLogger when enabled' do
+ end
+
+ describe 'static' do
+ it 'is disabled on Base' do
+ assert ! @base.static?
+ end
+
+ it 'is enabled on Default' do
+ assert @default.static?
+ end
+
+ # TODO: it setup static routes if public is enabled
+ # TODO: however, that's already tested in static_test so...
+ end
+
+ describe 'host' do
+ it 'defaults to 0.0.0.0' do
+ assert_equal '0.0.0.0', @base.host
+ assert_equal '0.0.0.0', @default.host
+ end
+ end
+
+ describe 'port' do
+ it 'defaults to 4567' do
+ assert_equal 4567, @base.port
+ assert_equal 4567, @default.port
+ end
+ end
+
+ describe 'server' do
+ it 'is one of thin, mongrel, webrick' do
+ assert_equal %w[thin mongrel webrick], @base.server
+ assert_equal %w[thin mongrel webrick], @default.server
+ end
+ end
+
+ describe 'app_file' do
+ it 'is nil' do
+ assert @base.app_file.nil?
+ assert @default.app_file.nil?
+ end
+ end
+
+ describe 'root' do
+ it 'is nil if app_file is not set' do
+ assert @base.root.nil?
+ assert @default.root.nil?
+ end
+
+ it 'is equal to the expanded basename of app_file' do
+ @base.app_file = __FILE__
+ assert_equal File.expand_path(File.dirname(__FILE__)), @base.root
+
+ @default.app_file = __FILE__
+ assert_equal File.expand_path(File.dirname(__FILE__)), @default.root
+ end
+ end
+
+ describe 'views' do
+ it 'is nil if root is not set' do
+ assert @base.views.nil?
+ assert @default.views.nil?
+ end
+
+ it 'is set to root joined with views/' do
+ @base.root = File.dirname(__FILE__)
+ assert_equal File.dirname(__FILE__) + "/views", @base.views
+
+ @default.root = File.dirname(__FILE__)
+ assert_equal File.dirname(__FILE__) + "/views", @default.views
+ end
+ end
+
+ describe 'public' do
+ it 'is nil if root is not set' do
+ assert @base.public.nil?
+ assert @default.public.nil?
+ end
+
+ it 'is set to root joined with public/' do
+ @base.root = File.dirname(__FILE__)
+ assert_equal File.dirname(__FILE__) + "/public", @base.public
+
+ @default.root = File.dirname(__FILE__)
+ assert_equal File.dirname(__FILE__) + "/public", @default.public
+ end
+ end
+
+ describe 'lock' do
+ it 'is disabled by default' do
+ assert ! @base.lock?
+ end
+ end
+end
diff --git a/vendor/sinatra/test/render_backtrace_test.rb b/vendor/sinatra/test/render_backtrace_test.rb
new file mode 100644
index 0000000..350beba
--- /dev/null
+++ b/vendor/sinatra/test/render_backtrace_test.rb
@@ -0,0 +1,145 @@
+require File.dirname(__FILE__) + '/helper'
+
+require 'sass/error'
+
+class RenderBacktraceTest < Test::Unit::TestCase
+ VIEWS = File.dirname(__FILE__) + '/views'
+
+ def assert_raise_at(filename, line, exception = RuntimeError)
+ f, l = nil
+ assert_raise(exception) do
+ begin
+ get('/')
+ rescue => e
+ f, l = e.backtrace.first.split(':')
+ raise
+ end
+ end
+ assert_equal(filename, f, "expected #{exception.name} in #{filename}, was #{f}")
+ assert_equal(line, l.to_i, "expected #{exception.name} in #{filename} at line #{line}, was at line #{l}")
+ end
+
+ def backtrace_app(&block)
+ mock_app {
+ use_in_file_templates!
+ set :views, RenderBacktraceTest::VIEWS
+ template :builder_template do
+ 'raise "error"'
+ end
+ template :erb_template do
+ '<% raise "error" %>'
+ end
+ template :haml_template do
+ '%h1= raise "error"'
+ end
+ template :sass_template do
+ '+syntax-error'
+ end
+ get '/', &block
+ }
+ end
+
+ it "provides backtrace for Builder template" do
+ backtrace_app { builder :error }
+ assert_raise_at(File.join(VIEWS,'error.builder'), 2)
+ end
+
+ it "provides backtrace for ERB template" do
+ backtrace_app { erb :error }
+ assert_raise_at(File.join(VIEWS,'error.erb'), 2)
+ end
+
+ it "provides backtrace for HAML template" do
+ backtrace_app { haml :error }
+ assert_raise_at(File.join(VIEWS,'error.haml'), 2)
+ end
+
+ it "provides backtrace for Sass template" do
+ backtrace_app { sass :error }
+ assert_raise_at(File.join(VIEWS,'error.sass'), 2, Sass::SyntaxError)
+ end
+
+ it "provides backtrace for ERB template with locals" do
+ backtrace_app { erb :error, {}, :french => true }
+ assert_raise_at(File.join(VIEWS,'error.erb'), 3)
+ end
+
+ it "provides backtrace for HAML template with locals" do
+ backtrace_app { haml :error, {}, :french => true }
+ assert_raise_at(File.join(VIEWS,'error.haml'), 3)
+ end
+
+ it "provides backtrace for inline Builder string" do
+ backtrace_app { builder "raise 'Ack! Thbbbt!'"}
+ assert_raise_at(__FILE__, (__LINE__-1))
+ end
+
+ it "provides backtrace for inline ERB string" do
+ backtrace_app { erb "<% raise 'bidi-bidi-bidi' %>" }
+ assert_raise_at(__FILE__, (__LINE__-1))
+ end
+
+ it "provides backtrace for inline HAML string" do
+ backtrace_app { haml "%h1= raise 'Lions and tigers and bears! Oh, my!'" }
+ assert_raise_at(__FILE__, (__LINE__-1))
+ end
+
+ # it "provides backtrace for inline Sass string" do
+ # backtrace_app { sass '+buh-bye' }
+ # assert_raise_at(__FILE__, (__LINE__-1), Sass::SyntaxError)
+ # end
+
+ it "provides backtrace for named Builder template" do
+ backtrace_app { builder :builder_template }
+ assert_raise_at(__FILE__, (__LINE__-68))
+ end
+
+ it "provides backtrace for named ERB template" do
+ backtrace_app { erb :erb_template }
+ assert_raise_at(__FILE__, (__LINE__-70))
+ end
+
+ it "provides backtrace for named HAML template" do
+ backtrace_app { haml :haml_template }
+ assert_raise_at(__FILE__, (__LINE__-72))
+ end
+
+ # it "provides backtrace for named Sass template" do
+ # backtrace_app { sass :sass_template }
+ # assert_raise_at(__FILE__, (__LINE__-74), Sass::SyntaxError)
+ # end
+
+ it "provides backtrace for in file Builder template" do
+ backtrace_app { builder :builder_in_file }
+ assert_raise_at(__FILE__, (__LINE__+22))
+ end
+
+ it "provides backtrace for in file ERB template" do
+ backtrace_app { erb :erb_in_file }
+ assert_raise_at(__FILE__, (__LINE__+20))
+ end
+
+ it "provides backtrace for in file HAML template" do
+ backtrace_app { haml :haml_in_file }
+ assert_raise_at(__FILE__, (__LINE__+18))
+ end
+
+ # it "provides backtrace for in file Sass template" do
+ # backtrace_app { sass :sass_in_file }
+ # assert_raise_at(__FILE__, (__LINE__+16), Sass::SyntaxError)
+ # end
+end
+
+__END__
+
+@@ builder_in_file
+raise "bif"
+
+@@ erb_in_file
+<% raise "bam" %>
+
+@@ haml_in_file
+%h1= raise "pow"
+
+@@ sass_in_file
++blam
diff --git a/vendor/sinatra/test/request_test.rb b/vendor/sinatra/test/request_test.rb
new file mode 100644
index 0000000..44dac6c
--- /dev/null
+++ b/vendor/sinatra/test/request_test.rb
@@ -0,0 +1,18 @@
+require File.dirname(__FILE__) + '/helper'
+
+class RequestTest < Test::Unit::TestCase
+ it 'responds to #user_agent' do
+ request = Sinatra::Request.new({'HTTP_USER_AGENT' => 'Test'})
+ assert request.respond_to?(:user_agent)
+ assert_equal 'Test', request.user_agent
+ end
+
+ it 'parses POST params when Content-Type is form-dataish' do
+ request = Sinatra::Request.new(
+ 'REQUEST_METHOD' => 'PUT',
+ 'CONTENT_TYPE' => 'application/x-www-form-urlencoded',
+ 'rack.input' => StringIO.new('foo=bar')
+ )
+ assert_equal 'bar', request.params['foo']
+ end
+end
diff --git a/vendor/sinatra/test/response_test.rb b/vendor/sinatra/test/response_test.rb
new file mode 100644
index 0000000..5aa5f4e
--- /dev/null
+++ b/vendor/sinatra/test/response_test.rb
@@ -0,0 +1,42 @@
+# encoding: utf-8
+
+require File.dirname(__FILE__) + '/helper'
+
+class ResponseTest < Test::Unit::TestCase
+ setup do
+ @response = Sinatra::Response.new
+ end
+
+ it "initializes with 200, text/html, and empty body" do
+ assert_equal 200, @response.status
+ assert_equal 'text/html', @response['Content-Type']
+ assert_equal [], @response.body
+ end
+
+ it 'uses case insensitive headers' do
+ @response['content-type'] = 'application/foo'
+ assert_equal 'application/foo', @response['Content-Type']
+ assert_equal 'application/foo', @response['CONTENT-TYPE']
+ end
+
+ it 'writes to body' do
+ @response.body = 'Hello'
+ @response.write ' World'
+ assert_equal 'Hello World', @response.body
+ end
+
+ [204, 304].each do |status_code|
+ it "removes the Content-Type header and body when response status is #{status_code}" do
+ @response.status = status_code
+ @response.body = ['Hello World']
+ assert_equal [status_code, {}, []], @response.finish
+ end
+ end
+
+ it 'Calculates the Content-Length using the bytesize of the body' do
+ @response.body = ['Hello', 'World!', 'â']
+ status, headers, body = @response.finish
+ assert_equal '14', headers['Content-Length']
+ assert_equal @response.body, body
+ end
+end
diff --git a/vendor/sinatra/test/result_test.rb b/vendor/sinatra/test/result_test.rb
new file mode 100644
index 0000000..5100abf
--- /dev/null
+++ b/vendor/sinatra/test/result_test.rb
@@ -0,0 +1,98 @@
+require File.dirname(__FILE__) + '/helper'
+
+class ResultTest < Test::Unit::TestCase
+ it "sets response.body when result is a String" do
+ mock_app {
+ get '/' do
+ 'Hello World'
+ end
+ }
+
+ get '/'
+ assert ok?
+ assert_equal 'Hello World', body
+ end
+
+ it "sets response.body when result is an Array of Strings" do
+ mock_app {
+ get '/' do
+ ['Hello', 'World']
+ end
+ }
+
+ get '/'
+ assert ok?
+ assert_equal 'HelloWorld', body
+ end
+
+ it "sets response.body when result responds to #each" do
+ mock_app {
+ get '/' do
+ res = lambda { 'Hello World' }
+ def res.each ; yield call ; end
+ res
+ end
+ }
+
+ get '/'
+ assert ok?
+ assert_equal 'Hello World', body
+ end
+
+ it "sets response.body to [] when result is nil" do
+ mock_app {
+ get '/' do
+ nil
+ end
+ }
+
+ get '/'
+ assert ok?
+ assert_equal '', body
+ end
+
+ it "sets status, headers, and body when result is a Rack response tuple" do
+ mock_app {
+ get '/' do
+ [205, {'Content-Type' => 'foo/bar'}, 'Hello World']
+ end
+ }
+
+ get '/'
+ assert_equal 205, status
+ assert_equal 'foo/bar', response['Content-Type']
+ assert_equal 'Hello World', body
+ end
+
+ it "sets status and body when result is a two-tuple" do
+ mock_app {
+ get '/' do
+ [409, 'formula of']
+ end
+ }
+
+ get '/'
+ assert_equal 409, status
+ assert_equal 'formula of', body
+ end
+
+ it "raises a TypeError when result is a non two or three tuple Array" do
+ mock_app {
+ get '/' do
+ [409, 'formula of', 'something else', 'even more']
+ end
+ }
+
+ assert_raise(TypeError) { get '/' }
+ end
+
+ it "sets status when result is a Fixnum status code" do
+ mock_app {
+ get('/') { 205 }
+ }
+
+ get '/'
+ assert_equal 205, status
+ assert_equal '', body
+ end
+end
diff --git a/vendor/sinatra/test/route_added_hook_test.rb b/vendor/sinatra/test/route_added_hook_test.rb
new file mode 100644
index 0000000..08fdd92
--- /dev/null
+++ b/vendor/sinatra/test/route_added_hook_test.rb
@@ -0,0 +1,59 @@
+require File.dirname(__FILE__) + '/helper'
+
+module RouteAddedTest
+ @routes, @procs = [], []
+ def self.routes ; @routes ; end
+ def self.procs ; @procs ; end
+ def self.route_added(verb, path, proc)
+ @routes << [verb, path]
+ @procs << proc
+ end
+end
+
+class RouteAddedHookTest < Test::Unit::TestCase
+ setup {
+ RouteAddedTest.routes.clear
+ RouteAddedTest.procs.clear
+ }
+
+ it "should be notified of an added route" do
+ mock_app(Class.new(Sinatra::Base)) {
+ register RouteAddedTest
+ get('/') {}
+ }
+
+ assert_equal [["GET", "/"], ["HEAD", "/"]],
+ RouteAddedTest.routes
+ end
+
+ it "should include hooks from superclass" do
+ a = Class.new(Class.new(Sinatra::Base))
+ b = Class.new(a)
+
+ a.register RouteAddedTest
+ b.class_eval { post("/sub_app_route") {} }
+
+ assert_equal [["POST", "/sub_app_route"]],
+ RouteAddedTest.routes
+ end
+
+ it "should only run once per extension" do
+ mock_app(Class.new(Sinatra::Base)) {
+ register RouteAddedTest
+ register RouteAddedTest
+ get('/') {}
+ }
+
+ assert_equal [["GET", "/"], ["HEAD", "/"]],
+ RouteAddedTest.routes
+ end
+
+ it "should pass route blocks as an argument" do
+ mock_app(Class.new(Sinatra::Base)) {
+ register RouteAddedTest
+ get('/') {}
+ }
+
+ assert_kind_of Proc, RouteAddedTest.procs.first
+ end
+end
diff --git a/vendor/sinatra/test/routing_test.rb b/vendor/sinatra/test/routing_test.rb
new file mode 100644
index 0000000..baceafe
--- /dev/null
+++ b/vendor/sinatra/test/routing_test.rb
@@ -0,0 +1,819 @@
+require File.dirname(__FILE__) + '/helper'
+
+# Helper method for easy route pattern matching testing
+def route_def(pattern)
+ mock_app { get(pattern) { } }
+end
+
+class RegexpLookAlike
+ class MatchData
+ def captures
+ ["this", "is", "a", "test"]
+ end
+ end
+
+ def match(string)
+ ::RegexpLookAlike::MatchData.new if string == "/this/is/a/test/"
+ end
+
+ def keys
+ ["one", "two", "three", "four"]
+ end
+end
+
+class RoutingTest < Test::Unit::TestCase
+ %w[get put post delete].each do |verb|
+ it "defines #{verb.upcase} request handlers with #{verb}" do
+ mock_app {
+ send verb, '/hello' do
+ 'Hello World'
+ end
+ }
+
+ request = Rack::MockRequest.new(@app)
+ response = request.request(verb.upcase, '/hello', {})
+ assert response.ok?
+ assert_equal 'Hello World', response.body
+ end
+ end
+
+ it "defines HEAD request handlers with HEAD" do
+ mock_app {
+ head '/hello' do
+ response['X-Hello'] = 'World!'
+ 'remove me'
+ end
+ }
+
+ request = Rack::MockRequest.new(@app)
+ response = request.request('HEAD', '/hello', {})
+ assert response.ok?
+ assert_equal 'World!', response['X-Hello']
+ assert_equal '', response.body
+ end
+
+ it "404s when no route satisfies the request" do
+ mock_app {
+ get('/foo') { }
+ }
+ get '/bar'
+ assert_equal 404, status
+ end
+
+ it "overrides the content-type in error handlers" do
+ mock_app {
+ before { content_type 'text/plain' }
+ error Sinatra::NotFound do
+ content_type "text/html"
+ "<h1>Not Found</h1>"
+ end
+ }
+
+ get '/foo'
+ assert_equal 404, status
+ assert_equal 'text/html', response["Content-Type"]
+ assert_equal "<h1>Not Found</h1>", response.body
+ end
+
+ it 'takes multiple definitions of a route' do
+ mock_app {
+ user_agent(/Foo/)
+ get '/foo' do
+ 'foo'
+ end
+
+ get '/foo' do
+ 'not foo'
+ end
+ }
+
+ get '/foo', {}, 'HTTP_USER_AGENT' => 'Foo'
+ assert ok?
+ assert_equal 'foo', body
+
+ get '/foo'
+ assert ok?
+ assert_equal 'not foo', body
+ end
+
+ it "exposes params with indifferent hash" do
+ mock_app {
+ get '/:foo' do
+ assert_equal 'bar', params['foo']
+ assert_equal 'bar', params[:foo]
+ 'well, alright'
+ end
+ }
+ get '/bar'
+ assert_equal 'well, alright', body
+ end
+
+ it "merges named params and query string params in params" do
+ mock_app {
+ get '/:foo' do
+ assert_equal 'bar', params['foo']
+ assert_equal 'biz', params['baz']
+ end
+ }
+ get '/bar?baz=biz'
+ assert ok?
+ end
+
+ it "supports named params like /hello/:person" do
+ mock_app {
+ get '/hello/:person' do
+ "Hello #{params['person']}"
+ end
+ }
+ get '/hello/Frank'
+ assert_equal 'Hello Frank', body
+ end
+
+ it "supports optional named params like /?:foo?/?:bar?" do
+ mock_app {
+ get '/?:foo?/?:bar?' do
+ "foo=#{params[:foo]};bar=#{params[:bar]}"
+ end
+ }
+
+ get '/hello/world'
+ assert ok?
+ assert_equal "foo=hello;bar=world", body
+
+ get '/hello'
+ assert ok?
+ assert_equal "foo=hello;bar=", body
+
+ get '/'
+ assert ok?
+ assert_equal "foo=;bar=", body
+ end
+
+ it "supports single splat params like /*" do
+ mock_app {
+ get '/*' do
+ assert params['splat'].kind_of?(Array)
+ params['splat'].join "\n"
+ end
+ }
+
+ get '/foo'
+ assert_equal "foo", body
+
+ get '/foo/bar/baz'
+ assert_equal "foo/bar/baz", body
+ end
+
+ it "supports mixing multiple splat params like /*/foo/*/*" do
+ mock_app {
+ get '/*/foo/*/*' do
+ assert params['splat'].kind_of?(Array)
+ params['splat'].join "\n"
+ end
+ }
+
+ get '/bar/foo/bling/baz/boom'
+ assert_equal "bar\nbling\nbaz/boom", body
+
+ get '/bar/foo/baz'
+ assert not_found?
+ end
+
+ it "supports mixing named and splat params like /:foo/*" do
+ mock_app {
+ get '/:foo/*' do
+ assert_equal 'foo', params['foo']
+ assert_equal ['bar/baz'], params['splat']
+ end
+ }
+
+ get '/foo/bar/baz'
+ assert ok?
+ end
+
+ it "matches a dot ('.') as part of a named param" do
+ mock_app {
+ get '/:foo/:bar' do
+ params[:foo]
+ end
+ }
+
+ get '/user@example.com/name'
+ assert_equal 200, response.status
+ assert_equal 'user@example.com', body
+ end
+
+ it "matches a literal dot ('.') outside of named params" do
+ mock_app {
+ get '/:file.:ext' do
+ assert_equal 'pony', params[:file]
+ assert_equal 'jpg', params[:ext]
+ 'right on'
+ end
+ }
+
+ get '/pony.jpg'
+ assert_equal 200, response.status
+ assert_equal 'right on', body
+ end
+
+ it "literally matches . in paths" do
+ route_def '/test.bar'
+
+ get '/test.bar'
+ assert ok?
+ get 'test0bar'
+ assert not_found?
+ end
+
+ it "literally matches $ in paths" do
+ route_def '/test$/'
+
+ get '/test$/'
+ assert ok?
+ end
+
+ it "literally matches + in paths" do
+ route_def '/te+st/'
+
+ get '/te%2Bst/'
+ assert ok?
+ get '/teeeeeeest/'
+ assert not_found?
+ end
+
+ it "literally matches () in paths" do
+ route_def '/test(bar)/'
+
+ get '/test(bar)/'
+ assert ok?
+ end
+
+ it "supports basic nested params" do
+ mock_app {
+ get '/hi' do
+ params["person"]["name"]
+ end
+ }
+
+ get "/hi?person[name]=John+Doe"
+ assert ok?
+ assert_equal "John Doe", body
+ end
+
+ it "exposes nested params with indifferent hash" do
+ mock_app {
+ get '/testme' do
+ assert_equal 'baz', params['bar']['foo']
+ assert_equal 'baz', params['bar'][:foo]
+ 'well, alright'
+ end
+ }
+ get '/testme?bar[foo]=baz'
+ assert_equal 'well, alright', body
+ end
+
+ it "supports deeply nested params" do
+ expected_params = {
+ "emacs" => {
+ "map" => { "goto-line" => "M-g g" },
+ "version" => "22.3.1"
+ },
+ "browser" => {
+ "firefox" => {"engine" => {"name"=>"spidermonkey", "version"=>"1.7.0"}},
+ "chrome" => {"engine" => {"name"=>"V8", "version"=>"1.0"}}
+ },
+ "paste" => {"name"=>"hello world", "syntax"=>"ruby"}
+ }
+ mock_app {
+ get '/foo' do
+ assert_equal expected_params, params
+ 'looks good'
+ end
+ }
+ get '/foo', expected_params
+ assert ok?
+ assert_equal 'looks good', body
+ end
+
+ it "preserves non-nested params" do
+ mock_app {
+ get '/foo' do
+ assert_equal "2", params["article_id"]
+ assert_equal "awesome", params['comment']['body']
+ assert_nil params['comment[body]']
+ 'looks good'
+ end
+ }
+
+ get '/foo?article_id=2&comment[body]=awesome'
+ assert ok?
+ assert_equal 'looks good', body
+ end
+
+ it "matches paths that include spaces encoded with %20" do
+ mock_app {
+ get '/path with spaces' do
+ 'looks good'
+ end
+ }
+
+ get '/path%20with%20spaces'
+ assert ok?
+ assert_equal 'looks good', body
+ end
+
+ it "matches paths that include spaces encoded with +" do
+ mock_app {
+ get '/path with spaces' do
+ 'looks good'
+ end
+ }
+
+ get '/path+with+spaces'
+ assert ok?
+ assert_equal 'looks good', body
+ end
+
+ it "URL decodes named parameters and splats" do
+ mock_app {
+ get '/:foo/*' do
+ assert_equal 'hello world', params['foo']
+ assert_equal ['how are you'], params['splat']
+ nil
+ end
+ }
+
+ get '/hello%20world/how%20are%20you'
+ assert ok?
+ end
+
+ it 'supports regular expressions' do
+ mock_app {
+ get(/^\/foo...\/bar$/) do
+ 'Hello World'
+ end
+ }
+
+ get '/foooom/bar'
+ assert ok?
+ assert_equal 'Hello World', body
+ end
+
+ it 'makes regular expression captures available in params[:captures]' do
+ mock_app {
+ get(/^\/fo(.*)\/ba(.*)/) do
+ assert_equal ['orooomma', 'f'], params[:captures]
+ 'right on'
+ end
+ }
+
+ get '/foorooomma/baf'
+ assert ok?
+ assert_equal 'right on', body
+ end
+
+ it 'supports regular expression look-alike routes' do
+ mock_app {
+ get(RegexpLookAlike.new) do
+ assert_equal 'this', params[:one]
+ assert_equal 'is', params[:two]
+ assert_equal 'a', params[:three]
+ assert_equal 'test', params[:four]
+ 'right on'
+ end
+ }
+
+ get '/this/is/a/test/'
+ assert ok?
+ assert_equal 'right on', body
+ end
+
+ it 'raises a TypeError when pattern is not a String or Regexp' do
+ assert_raise(TypeError) {
+ mock_app { get(42){} }
+ }
+ end
+
+ it "returns response immediately on halt" do
+ mock_app {
+ get '/' do
+ halt 'Hello World'
+ 'Boo-hoo World'
+ end
+ }
+
+ get '/'
+ assert ok?
+ assert_equal 'Hello World', body
+ end
+
+ it "halts with a response tuple" do
+ mock_app {
+ get '/' do
+ halt 295, {'Content-Type' => 'text/plain'}, 'Hello World'
+ end
+ }
+
+ get '/'
+ assert_equal 295, status
+ assert_equal 'text/plain', response['Content-Type']
+ assert_equal 'Hello World', body
+ end
+
+ it "halts with an array of strings" do
+ mock_app {
+ get '/' do
+ halt %w[Hello World How Are You]
+ end
+ }
+
+ get '/'
+ assert_equal 'HelloWorldHowAreYou', body
+ end
+
+ it "transitions to the next matching route on pass" do
+ mock_app {
+ get '/:foo' do
+ pass
+ 'Hello Foo'
+ end
+
+ get '/*' do
+ assert !params.include?('foo')
+ 'Hello World'
+ end
+ }
+
+ get '/bar'
+ assert ok?
+ assert_equal 'Hello World', body
+ end
+
+ it "transitions to 404 when passed and no subsequent route matches" do
+ mock_app {
+ get '/:foo' do
+ pass
+ 'Hello Foo'
+ end
+ }
+
+ get '/bar'
+ assert not_found?
+ end
+
+ it "passes when matching condition returns false" do
+ mock_app {
+ condition { params[:foo] == 'bar' }
+ get '/:foo' do
+ 'Hello World'
+ end
+ }
+
+ get '/bar'
+ assert ok?
+ assert_equal 'Hello World', body
+
+ get '/foo'
+ assert not_found?
+ end
+
+ it "does not pass when matching condition returns nil" do
+ mock_app {
+ condition { nil }
+ get '/:foo' do
+ 'Hello World'
+ end
+ }
+
+ get '/bar'
+ assert ok?
+ assert_equal 'Hello World', body
+ end
+
+ it "passes to next route when condition calls pass explicitly" do
+ mock_app {
+ condition { pass unless params[:foo] == 'bar' }
+ get '/:foo' do
+ 'Hello World'
+ end
+ }
+
+ get '/bar'
+ assert ok?
+ assert_equal 'Hello World', body
+
+ get '/foo'
+ assert not_found?
+ end
+
+ it "passes to the next route when host_name does not match" do
+ mock_app {
+ host_name 'example.com'
+ get '/foo' do
+ 'Hello World'
+ end
+ }
+ get '/foo'
+ assert not_found?
+
+ get '/foo', {}, { 'HTTP_HOST' => 'example.com' }
+ assert_equal 200, status
+ assert_equal 'Hello World', body
+ end
+
+ it "passes to the next route when user_agent does not match" do
+ mock_app {
+ user_agent(/Foo/)
+ get '/foo' do
+ 'Hello World'
+ end
+ }
+ get '/foo'
+ assert not_found?
+
+ get '/foo', {}, { 'HTTP_USER_AGENT' => 'Foo Bar' }
+ assert_equal 200, status
+ assert_equal 'Hello World', body
+ end
+
+ it "makes captures in user agent pattern available in params[:agent]" do
+ mock_app {
+ user_agent(/Foo (.*)/)
+ get '/foo' do
+ 'Hello ' + params[:agent].first
+ end
+ }
+ get '/foo', {}, { 'HTTP_USER_AGENT' => 'Foo Bar' }
+ assert_equal 200, status
+ assert_equal 'Hello Bar', body
+ end
+
+ it "filters by accept header" do
+ mock_app {
+ get '/', :provides => :xml do
+ request.env['HTTP_ACCEPT']
+ end
+ }
+
+ get '/', {}, { 'HTTP_ACCEPT' => 'application/xml' }
+ assert ok?
+ assert_equal 'application/xml', body
+ assert_equal 'application/xml', response.headers['Content-Type']
+
+ get '/', {}, { :accept => 'text/html' }
+ assert !ok?
+ end
+
+ it "allows multiple mime types for accept header" do
+ types = ['image/jpeg', 'image/pjpeg']
+
+ mock_app {
+ get '/', :provides => types do
+ request.env['HTTP_ACCEPT']
+ end
+ }
+
+ types.each do |type|
+ get '/', {}, { 'HTTP_ACCEPT' => type }
+ assert ok?
+ assert_equal type, body
+ assert_equal type, response.headers['Content-Type']
+ end
+ end
+
+ it 'degrades gracefully when optional accept header is not provided' do
+ mock_app {
+ get '/', :provides => :xml do
+ request.env['HTTP_ACCEPT']
+ end
+ get '/' do
+ 'default'
+ end
+ }
+ get '/'
+ assert ok?
+ assert_equal 'default', body
+ end
+
+ it 'passes a single url param as block parameters when one param is specified' do
+ mock_app {
+ get '/:foo' do |foo|
+ assert_equal 'bar', foo
+ end
+ }
+
+ get '/bar'
+ assert ok?
+ end
+
+ it 'passes multiple params as block parameters when many are specified' do
+ mock_app {
+ get '/:foo/:bar/:baz' do |foo, bar, baz|
+ assert_equal 'abc', foo
+ assert_equal 'def', bar
+ assert_equal 'ghi', baz
+ end
+ }
+
+ get '/abc/def/ghi'
+ assert ok?
+ end
+
+ it 'passes regular expression captures as block parameters' do
+ mock_app {
+ get(/^\/fo(.*)\/ba(.*)/) do |foo, bar|
+ assert_equal 'orooomma', foo
+ assert_equal 'f', bar
+ 'looks good'
+ end
+ }
+
+ get '/foorooomma/baf'
+ assert ok?
+ assert_equal 'looks good', body
+ end
+
+ it "supports mixing multiple splat params like /*/foo/*/* as block parameters" do
+ mock_app {
+ get '/*/foo/*/*' do |foo, bar, baz|
+ assert_equal 'bar', foo
+ assert_equal 'bling', bar
+ assert_equal 'baz/boom', baz
+ 'looks good'
+ end
+ }
+
+ get '/bar/foo/bling/baz/boom'
+ assert ok?
+ assert_equal 'looks good', body
+ end
+
+ it 'raises an ArgumentError with block arity > 1 and too many values' do
+ mock_app {
+ get '/:foo/:bar/:baz' do |foo, bar|
+ 'quux'
+ end
+ }
+
+ assert_raise(ArgumentError) { get '/a/b/c' }
+ end
+
+ it 'raises an ArgumentError with block param arity > 1 and too few values' do
+ mock_app {
+ get '/:foo/:bar' do |foo, bar, baz|
+ 'quux'
+ end
+ }
+
+ assert_raise(ArgumentError) { get '/a/b' }
+ end
+
+ it 'succeeds if no block parameters are specified' do
+ mock_app {
+ get '/:foo/:bar' do
+ 'quux'
+ end
+ }
+
+ get '/a/b'
+ assert ok?
+ assert_equal 'quux', body
+ end
+
+ it 'passes all params with block param arity -1 (splat args)' do
+ mock_app {
+ get '/:foo/:bar' do |*args|
+ args.join
+ end
+ }
+
+ get '/a/b'
+ assert ok?
+ assert_equal 'ab', body
+ end
+
+ it 'allows custom route-conditions to be set via route options' do
+ protector = Module.new {
+ def protect(*args)
+ condition {
+ unless authorize(params["user"], params["password"])
+ halt 403, "go away"
+ end
+ }
+ end
+ }
+
+ mock_app {
+ register protector
+
+ helpers do
+ def authorize(username, password)
+ username == "foo" && password == "bar"
+ end
+ end
+
+ get "/", :protect => true do
+ "hey"
+ end
+ }
+
+ get "/"
+ assert forbidden?
+ assert_equal "go away", body
+
+ get "/", :user => "foo", :password => "bar"
+ assert ok?
+ assert_equal "hey", body
+ end
+
+ # NOTE Block params behaves differently under 1.8 and 1.9. Under 1.8, block
+ # param arity is lax: declaring a mismatched number of block params results
+ # in a warning. Under 1.9, block param arity is strict: mismatched block
+ # arity raises an ArgumentError.
+
+ if RUBY_VERSION >= '1.9'
+
+ it 'raises an ArgumentError with block param arity 1 and no values' do
+ mock_app {
+ get '/foo' do |foo|
+ 'quux'
+ end
+ }
+
+ assert_raise(ArgumentError) { get '/foo' }
+ end
+
+ it 'raises an ArgumentError with block param arity 1 and too many values' do
+ mock_app {
+ get '/:foo/:bar/:baz' do |foo|
+ 'quux'
+ end
+ }
+
+ assert_raise(ArgumentError) { get '/a/b/c' }
+ end
+
+ else
+
+ it 'does not raise an ArgumentError with block param arity 1 and no values' do
+ mock_app {
+ get '/foo' do |foo|
+ 'quux'
+ end
+ }
+
+ silence_warnings { get '/foo' }
+ assert ok?
+ assert_equal 'quux', body
+ end
+
+ it 'does not raise an ArgumentError with block param arity 1 and too many values' do
+ mock_app {
+ get '/:foo/:bar/:baz' do |foo|
+ 'quux'
+ end
+ }
+
+ silence_warnings { get '/a/b/c' }
+ assert ok?
+ assert_equal 'quux', body
+ end
+
+ end
+
+ it "matches routes defined in superclasses" do
+ base = Class.new(Sinatra::Base)
+ base.get('/foo') { 'foo in baseclass' }
+
+ mock_app(base) {
+ get('/bar') { 'bar in subclass' }
+ }
+
+ get '/foo'
+ assert ok?
+ assert_equal 'foo in baseclass', body
+
+ get '/bar'
+ assert ok?
+ assert_equal 'bar in subclass', body
+ end
+
+ it "matches routes in subclasses before superclasses" do
+ base = Class.new(Sinatra::Base)
+ base.get('/foo') { 'foo in baseclass' }
+ base.get('/bar') { 'bar in baseclass' }
+
+ mock_app(base) {
+ get('/foo') { 'foo in subclass' }
+ }
+
+ get '/foo'
+ assert ok?
+ assert_equal 'foo in subclass', body
+
+ get '/bar'
+ assert ok?
+ assert_equal 'bar in baseclass', body
+ end
+end
diff --git a/vendor/sinatra/test/sass_test.rb b/vendor/sinatra/test/sass_test.rb
new file mode 100644
index 0000000..c8d6a73
--- /dev/null
+++ b/vendor/sinatra/test/sass_test.rb
@@ -0,0 +1,79 @@
+require File.dirname(__FILE__) + '/helper'
+require 'sass'
+
+class SassTest < Test::Unit::TestCase
+ def sass_app(&block)
+ mock_app {
+ set :views, File.dirname(__FILE__) + '/views'
+ get '/', &block
+ }
+ get '/'
+ end
+
+ it 'renders inline Sass strings' do
+ sass_app { sass "#sass\n :background-color #FFF\n" }
+ assert ok?
+ assert_equal "#sass {\n background-color: #FFF; }\n", body
+ end
+
+ it 'renders .sass files in views path' do
+ sass_app { sass :hello }
+ assert ok?
+ assert_equal "#sass {\n background-color: #FFF; }\n", body
+ end
+
+ it 'ignores the layout option' do
+ sass_app { sass :hello, :layout => :layout2 }
+ assert ok?
+ assert_equal "#sass {\n background-color: #FFF; }\n", body
+ end
+
+ it "raises error if template not found" do
+ mock_app {
+ get('/') { sass :no_such_template }
+ }
+ assert_raise(Errno::ENOENT) { get('/') }
+ end
+
+ it "passes SASS options to the Sass engine" do
+ sass_app {
+ sass "#sass\n :background-color #FFF\n :color #000\n", :style => :compact
+ }
+ assert ok?
+ assert_equal "#sass { background-color: #FFF; color: #000; }\n", body
+ end
+
+ it "passes default SASS options to the Sass engine" do
+ mock_app {
+ set :sass, {:style => :compact} # default Sass style is :nested
+ get '/' do
+ sass "#sass\n :background-color #FFF\n :color #000\n"
+ end
+ }
+ get '/'
+ assert ok?
+ assert_equal "#sass { background-color: #FFF; color: #000; }\n", body
+ end
+
+ it "merges the default SASS options with the overrides and passes them to the Sass engine" do
+ mock_app {
+ set :sass, {:style => :compact, :attribute_syntax => :alternate } # default Sass attribute_syntax is :normal (with : in front)
+ get '/' do
+ sass "#sass\n background-color: #FFF\n color: #000\n"
+ end
+ get '/raised' do
+ sass "#sass\n :background-color #FFF\n :color #000\n", :style => :expanded # retains global attribute_syntax settings
+ end
+ get '/expanded_normal' do
+ sass "#sass\n :background-color #FFF\n :color #000\n", :style => :expanded, :attribute_syntax => :normal
+ end
+ }
+ get '/'
+ assert ok?
+ assert_equal "#sass { background-color: #FFF; color: #000; }\n", body
+ assert_raise(Sass::SyntaxError) { get('/raised') }
+ get '/expanded_normal'
+ assert ok?
+ assert_equal "#sass {\n background-color: #FFF;\n color: #000;\n}\n", body
+ end
+end
diff --git a/vendor/sinatra/test/server_test.rb b/vendor/sinatra/test/server_test.rb
new file mode 100644
index 0000000..76d4ef9
--- /dev/null
+++ b/vendor/sinatra/test/server_test.rb
@@ -0,0 +1,47 @@
+require File.dirname(__FILE__) + '/helper'
+
+module Rack::Handler
+ class Mock
+ extend Test::Unit::Assertions
+
+ def self.run(app, options={})
+ assert(app < Sinatra::Base)
+ assert_equal 9001, options[:Port]
+ assert_equal 'foo.local', options[:Host]
+ yield new
+ end
+
+ def stop
+ end
+ end
+
+ register 'mock', 'Rack::Handler::Mock'
+end
+
+class ServerTest < Test::Unit::TestCase
+ setup do
+ mock_app {
+ set :server, 'mock'
+ set :host, 'foo.local'
+ set :port, 9001
+ }
+ $stdout = File.open('/dev/null', 'wb')
+ end
+
+ def teardown
+ $stdout = STDOUT
+ end
+
+ it "locates the appropriate Rack handler and calls ::run" do
+ @app.run!
+ end
+
+ it "sets options on the app before running" do
+ @app.run! :sessions => true
+ assert @app.sessions?
+ end
+
+ it "falls back on the next server handler when not found" do
+ @app.run! :server => %w[foo bar mock]
+ end
+end
diff --git a/vendor/sinatra/test/sinatra_test.rb b/vendor/sinatra/test/sinatra_test.rb
new file mode 100644
index 0000000..5c695b2
--- /dev/null
+++ b/vendor/sinatra/test/sinatra_test.rb
@@ -0,0 +1,13 @@
+require File.dirname(__FILE__) + '/helper'
+
+class SinatraTest < Test::Unit::TestCase
+ it 'creates a new Sinatra::Base subclass on new' do
+ app =
+ Sinatra.new do
+ get '/' do
+ 'Hello World'
+ end
+ end
+ assert_same Sinatra::Base, app.superclass
+ end
+end
diff --git a/vendor/sinatra/test/static_test.rb b/vendor/sinatra/test/static_test.rb
new file mode 100644
index 0000000..7df3c63
--- /dev/null
+++ b/vendor/sinatra/test/static_test.rb
@@ -0,0 +1,87 @@
+require File.dirname(__FILE__) + '/helper'
+
+class StaticTest < Test::Unit::TestCase
+ setup do
+ mock_app {
+ set :static, true
+ set :public, File.dirname(__FILE__)
+ }
+ end
+
+ it 'serves GET requests for files in the public directory' do
+ get "/#{File.basename(__FILE__)}"
+ assert ok?
+ assert_equal File.read(__FILE__), body
+ assert_equal File.size(__FILE__).to_s, response['Content-Length']
+ assert response.headers.include?('Last-Modified')
+ end
+
+ it 'produces a body that can be iterated over multiple times' do
+ env = Rack::MockRequest.env_for("/#{File.basename(__FILE__)}")
+ status, headers, body = @app.call(env)
+ buf1, buf2 = [], []
+ body.each { |part| buf1 << part }
+ body.each { |part| buf2 << part }
+ assert_equal buf1.join, buf2.join
+ assert_equal File.read(__FILE__), buf1.join
+ end
+
+ it 'serves HEAD requests for files in the public directory' do
+ head "/#{File.basename(__FILE__)}"
+ assert ok?
+ assert_equal '', body
+ assert_equal File.size(__FILE__).to_s, response['Content-Length']
+ assert response.headers.include?('Last-Modified')
+ end
+
+ %w[POST PUT DELETE].each do |verb|
+ it "does not serve #{verb} requests" do
+ send verb.downcase, "/#{File.basename(__FILE__)}"
+ assert_equal 404, status
+ end
+ end
+
+ it 'serves files in preference to custom routes' do
+ @app.get("/#{File.basename(__FILE__)}") { 'Hello World' }
+ get "/#{File.basename(__FILE__)}"
+ assert ok?
+ assert body != 'Hello World'
+ end
+
+ it 'does not serve directories' do
+ get "/"
+ assert not_found?
+ end
+
+ it 'passes to the next handler when the static option is disabled' do
+ @app.set :static, false
+ get "/#{File.basename(__FILE__)}"
+ assert not_found?
+ end
+
+ it 'passes to the next handler when the public option is nil' do
+ @app.set :public, nil
+ get "/#{File.basename(__FILE__)}"
+ assert not_found?
+ end
+
+ it '404s when a file is not found' do
+ get "/foobarbaz.txt"
+ assert not_found?
+ end
+
+ it 'serves files when .. path traverses within public directory' do
+ get "/data/../#{File.basename(__FILE__)}"
+ assert ok?
+ assert_equal File.read(__FILE__), body
+ end
+
+ it '404s when .. path traverses outside of public directory' do
+ mock_app {
+ set :static, true
+ set :public, File.dirname(__FILE__) + '/data'
+ }
+ get "/../#{File.basename(__FILE__)}"
+ assert not_found?
+ end
+end
diff --git a/vendor/sinatra/test/templates_test.rb b/vendor/sinatra/test/templates_test.rb
new file mode 100644
index 0000000..7c9711c
--- /dev/null
+++ b/vendor/sinatra/test/templates_test.rb
@@ -0,0 +1,141 @@
+require File.dirname(__FILE__) + '/helper'
+
+class TemplatesTest < Test::Unit::TestCase
+ def render_app(base=Sinatra::Base, &block)
+ mock_app(base) {
+ def render_test(template, data, options, locals, &block)
+ inner = block ? block.call : ''
+ data + inner
+ end
+ set :views, File.dirname(__FILE__) + '/views'
+ get '/', &block
+ template(:layout3) { "Layout 3!\n" }
+ }
+ get '/'
+ end
+
+ def with_default_layout
+ layout = File.dirname(__FILE__) + '/views/layout.test'
+ File.open(layout, 'wb') { |io| io.write "Layout!\n" }
+ yield
+ ensure
+ File.unlink(layout) rescue nil
+ end
+
+ it 'renders String templates directly' do
+ render_app { render :test, 'Hello World' }
+ assert ok?
+ assert_equal 'Hello World', body
+ end
+
+ it 'renders Proc templates using the call result' do
+ render_app { render :test, Proc.new {'Hello World'} }
+ assert ok?
+ assert_equal 'Hello World', body
+ end
+
+ it 'looks up Symbol templates in views directory' do
+ render_app { render :test, :hello }
+ assert ok?
+ assert_equal "Hello World!\n", body
+ end
+
+ it 'uses the default layout template if not explicitly overridden' do
+ with_default_layout do
+ render_app { render :test, :hello }
+ assert ok?
+ assert_equal "Layout!\nHello World!\n", body
+ end
+ end
+
+ it 'uses the default layout template if not really overriden' do
+ with_default_layout do
+ render_app { render :test, :hello, :layout => true }
+ assert ok?
+ assert_equal "Layout!\nHello World!\n", body
+ end
+ end
+
+ it 'uses the layout template specified' do
+ render_app { render :test, :hello, :layout => :layout2 }
+ assert ok?
+ assert_equal "Layout 2!\nHello World!\n", body
+ end
+
+ it 'uses layout templates defined with the #template method' do
+ render_app { render :test, :hello, :layout => :layout3 }
+ assert ok?
+ assert_equal "Layout 3!\nHello World!\n", body
+ end
+
+ it 'loads templates from source file with use_in_file_templates!' do
+ mock_app {
+ use_in_file_templates!
+ }
+ assert_equal "this is foo\n\n", @app.templates[:foo][:template]
+ assert_equal "X\n= yield\nX\n", @app.templates[:layout][:template]
+ end
+
+ it 'loads templates from specified views directory' do
+ render_app { render :test, :hello, :views => options.views + '/foo' }
+
+ assert_equal "from another views directory\n", body
+ end
+
+ test 'use_in_file_templates simply ignores IO errors' do
+ assert_nothing_raised {
+ mock_app {
+ use_in_file_templates!('/foo/bar')
+ }
+ }
+
+ assert @app.templates.empty?
+ end
+
+ it 'passes locals to the layout' do
+ mock_app {
+ template :my_layout do
+ 'Hello <%= name %>!<%= yield %>'
+ end
+
+ get '/' do
+ erb '<p>content</p>', { :layout => :my_layout }, { :name => 'Mike'}
+ end
+ }
+
+ get '/'
+ assert ok?
+ assert_equal 'Hello Mike!<p>content</p>', body
+ end
+
+ it 'loads templates defined in subclasses' do
+ base = Class.new(Sinatra::Base)
+ base.template(:foo) { 'bar' }
+ render_app(base) { render :test, :foo }
+ assert ok?
+ assert_equal 'bar', body
+ end
+
+ it 'uses templates in superclasses before subclasses' do
+ base = Class.new(Sinatra::Base)
+ base.template(:foo) { 'template in superclass' }
+ render_app(base) { render :test, :foo }
+ @app.template(:foo) { 'template in subclass' }
+
+ get '/'
+ assert ok?
+ assert_equal 'template in subclass', body
+ end
+end
+
+# __END__ : this is not the real end of the script.
+
+__END__
+
+@@ foo
+this is foo
+
+@@ layout
+X
+= yield
+X
diff --git a/vendor/sinatra/test/views/error.builder b/vendor/sinatra/test/views/error.builder
new file mode 100644
index 0000000..9cf87d5
--- /dev/null
+++ b/vendor/sinatra/test/views/error.builder
@@ -0,0 +1,3 @@
+xml.error do
+ raise "goodbye"
+end
diff --git a/vendor/sinatra/test/views/error.erb b/vendor/sinatra/test/views/error.erb
new file mode 100644
index 0000000..b48d1f0
--- /dev/null
+++ b/vendor/sinatra/test/views/error.erb
@@ -0,0 +1,3 @@
+Hello <%= 'World' %>
+<% raise 'Goodbye' unless defined?(french) && french %>
+<% raise 'Au revoir' if defined?(french) && french %>
diff --git a/vendor/sinatra/test/views/error.haml b/vendor/sinatra/test/views/error.haml
new file mode 100644
index 0000000..6019007
--- /dev/null
+++ b/vendor/sinatra/test/views/error.haml
@@ -0,0 +1,3 @@
+%h1 Hello From Haml
+= raise 'goodbye' unless defined?(french) && french
+= raise 'au revoir' if defined?(french) && french
diff --git a/vendor/sinatra/test/views/error.sass b/vendor/sinatra/test/views/error.sass
new file mode 100644
index 0000000..42fc56b
--- /dev/null
+++ b/vendor/sinatra/test/views/error.sass
@@ -0,0 +1,2 @@
+#sass
+ +argle-bargle
diff --git a/vendor/sinatra/test/views/foo/hello.test b/vendor/sinatra/test/views/foo/hello.test
new file mode 100644
index 0000000..2aba634
--- /dev/null
+++ b/vendor/sinatra/test/views/foo/hello.test
@@ -0,0 +1 @@
+from another views directory
diff --git a/vendor/sinatra/test/views/hello.builder b/vendor/sinatra/test/views/hello.builder
new file mode 100644
index 0000000..16b86d0
--- /dev/null
+++ b/vendor/sinatra/test/views/hello.builder
@@ -0,0 +1 @@
+xml.exclaim "You're my boy, #{@name}!"
diff --git a/vendor/sinatra/test/views/hello.erb b/vendor/sinatra/test/views/hello.erb
new file mode 100644
index 0000000..bcbbc92
--- /dev/null
+++ b/vendor/sinatra/test/views/hello.erb
@@ -0,0 +1 @@
+Hello <%= 'World' %>
diff --git a/vendor/sinatra/test/views/hello.haml b/vendor/sinatra/test/views/hello.haml
new file mode 100644
index 0000000..d6852a6
--- /dev/null
+++ b/vendor/sinatra/test/views/hello.haml
@@ -0,0 +1 @@
+%h1 Hello From Haml
diff --git a/vendor/sinatra/test/views/hello.sass b/vendor/sinatra/test/views/hello.sass
new file mode 100644
index 0000000..5a4fd57
--- /dev/null
+++ b/vendor/sinatra/test/views/hello.sass
@@ -0,0 +1,2 @@
+#sass
+ :background-color #FFF
diff --git a/vendor/sinatra/test/views/hello.test b/vendor/sinatra/test/views/hello.test
new file mode 100644
index 0000000..980a0d5
--- /dev/null
+++ b/vendor/sinatra/test/views/hello.test
@@ -0,0 +1 @@
+Hello World!
diff --git a/vendor/sinatra/test/views/layout2.builder b/vendor/sinatra/test/views/layout2.builder
new file mode 100644
index 0000000..9491f57
--- /dev/null
+++ b/vendor/sinatra/test/views/layout2.builder
@@ -0,0 +1,3 @@
+xml.layout do
+ xml << yield
+end
diff --git a/vendor/sinatra/test/views/layout2.erb b/vendor/sinatra/test/views/layout2.erb
new file mode 100644
index 0000000..e097f3b
--- /dev/null
+++ b/vendor/sinatra/test/views/layout2.erb
@@ -0,0 +1,2 @@
+ERB Layout!
+<%= yield %>
diff --git a/vendor/sinatra/test/views/layout2.haml b/vendor/sinatra/test/views/layout2.haml
new file mode 100644
index 0000000..58bfc04
--- /dev/null
+++ b/vendor/sinatra/test/views/layout2.haml
@@ -0,0 +1,2 @@
+%h1 HAML Layout!
+%p= yield
diff --git a/vendor/sinatra/test/views/layout2.test b/vendor/sinatra/test/views/layout2.test
new file mode 100644
index 0000000..fb432e3
--- /dev/null
+++ b/vendor/sinatra/test/views/layout2.test
@@ -0,0 +1 @@
+Layout 2!
|
jstorimer/sinatra-shopify
|
f6affef9c2fd78b84a0db7c3f7ee5f4656b6cb06
|
Maybe I can't modify the LOAD_PATH.
|
diff --git a/app.rb b/app.rb
index d74def8..47a8399 100644
--- a/app.rb
+++ b/app.rb
@@ -1,21 +1,19 @@
require 'rubygems'
require 'sinatra'
-
-$:.unshift(File.dirname(__FILE__) + '/lib')
-require 'sinatra/shopify'
+require File.dirname(__FILE__) + '/lib/sinatra/shopify'
get '/' do
redirect '/home'
end
get '/home' do
authorize!
@products = ShopifyAPI::Product.find(:all, :params => {:limit => 3})
@orders = ShopifyAPI::Order.find(:all, :params => {:limit => 3, :order => "created_at DESC" })
erb :index
end
get '/design' do
erb :design
end
\ No newline at end of file
|
jstorimer/sinatra-shopify
|
405d3e046a5f29bc28f1958be16be11eebc0ba7c
|
Added gem manifest.
|
diff --git a/.gems b/.gems
new file mode 100644
index 0000000..69135a9
--- /dev/null
+++ b/.gems
@@ -0,0 +1 @@
+shopify_api
\ No newline at end of file
|
jstorimer/sinatra-shopify
|
a494b8c48491ef4e55b4dcb7a611bc78280ad1dd
|
Added rackup file.
|
diff --git a/config.ru b/config.ru
new file mode 100644
index 0000000..b9f5e88
--- /dev/null
+++ b/config.ru
@@ -0,0 +1,2 @@
+require 'app'
+run Sinatra::Application
\ No newline at end of file
|
jstorimer/sinatra-shopify
|
0c802ef3697a0bcb1daf5c6bf03943623c2f28e7
|
Added shopify_api gem dependency. Included default templates. Moved all authentication logic to lib/sinatra/shopify.rb
|
diff --git a/app.rb b/app.rb
index 50e2fe0..d74def8 100644
--- a/app.rb
+++ b/app.rb
@@ -1,8 +1,21 @@
require 'rubygems'
require 'sinatra'
+
+$:.unshift(File.dirname(__FILE__) + '/lib')
require 'sinatra/shopify'
get '/' do
+ redirect '/home'
+end
+
+get '/home' do
authorize!
+
+ @products = ShopifyAPI::Product.find(:all, :params => {:limit => 3})
+ @orders = ShopifyAPI::Order.find(:all, :params => {:limit => 3, :order => "created_at DESC" })
erb :index
+end
+
+get '/design' do
+ erb :design
end
\ No newline at end of file
diff --git a/lib/shopify.rb b/lib/sinatra/shopify.rb
similarity index 67%
rename from lib/shopify.rb
rename to lib/sinatra/shopify.rb
index 046890c..6698f62 100644
--- a/lib/shopify.rb
+++ b/lib/sinatra/shopify.rb
@@ -1,47 +1,65 @@
require 'sinatra/base'
+require 'active_support'
+require 'active_resource'
+
+gem 'shopify_api'
+require 'shopify_api'
module Sinatra
module Shopify
module Helpers
def current_shop
session[:shopify]
end
def authorize!
redirect '/login' unless current_shop
+
+ ActiveResource::Base.site = session[:shopify].site
end
def logout!
session[:shopify] = nil
end
end
def self.registered(app)
app.helpers Shopify::Helpers
+ app.enable :sessions
+
+ # load config file credentials
+ config = File.dirname(__FILE__) + "/shopify.yml"
+ credentials = YAML.load(File.read(config))
+ ShopifyAPI::Session.setup(credentials)
app.get '/login' do
erb :login
end
+
+ app.get '/logout' do
+ logout!
+ redirect '/'
+ end
app.post '/login/authenticate' do
redirect ShopifyAPI::Session.new(params[:shop]).create_permission_url
end
app.get '/login/finalize' do
shopify_session = ShopifyAPI::Session.new(params[:shop], params[:t])
if shopify_session.valid?
session[:shopify] = shopify_session
return_address = session[:return_to] || '/'
session[:return_to] = nil
redirect return_address
else
redirect '/login'
end
end
end
end
register Shopify
end
\ No newline at end of file
diff --git a/shopify_app b/shopify_app
deleted file mode 160000
index 6ae8538..0000000
--- a/shopify_app
+++ /dev/null
@@ -1 +0,0 @@
-Subproject commit 6ae8538fbf8a28cfea5f67353b11e68e47671604
diff --git a/views/design.erb b/views/design.erb
new file mode 100644
index 0000000..373f165
--- /dev/null
+++ b/views/design.erb
@@ -0,0 +1,164 @@
+<h1 class="blue">Overview of the styles used</h1>
+
+<div class="info">
+ <img src='/images/info.gif' style="float:left" />
+ <p>You are free to use this demo application as a base to create new applications that use the Shopify API.</p>
+</div>
+
+<table id="style-table">
+ <tr>
+ <td style="width: 33%">
+ <pre><code><h1>Lorem ipsum</h1></code></pre>
+ </td>
+
+ <td style="width: 66%">
+ <h1>Lorem ipsum</h1>
+ </td>
+ </tr>
+ <tr>
+ <td>
+ <pre><code><h2>Lorem ipsum</h2></code></pre>
+ </td>
+
+ <td>
+ <h2>Lorem ipsum</h2>
+ </td>
+ </tr>
+ <tr>
+ <td>
+ <pre><code><h3>Lorem ipsum</h3></code></pre>
+ </td>
+
+ <td>
+ <h3>Lorem ipsum</h3>
+ </td>
+ </tr>
+ <tr>
+ <td>
+ <pre><code><h4>Lorem ipsum</h4></code></pre>
+ </td>
+
+ <td>
+ <h4>Lorem ipsum</h4>
+ </td>
+ </tr>
+
+ <tr>
+ <td>
+ <pre><code><p>…</p></code></pre>
+ </td>
+
+ <td>
+ <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
+ </td>
+ </tr>
+
+ <tr>
+ <td>
+ <pre><code><p class="note">…</p></code></pre>
+ </td>
+
+ <td>
+ <p class="note">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
+ </td>
+ </tr>
+
+ <tr>
+ <td>
+ <pre><code><span class="highlight">…</span></code></pre>
+ </td>
+
+ <td>
+ <span class="highlight">Lorem ipsum dolor sit amet</p>
+ </td>
+ </tr>
+
+ <tr>
+ <td>
+ <pre><code><h3 class="blue">…</h3></code></pre>
+ </td>
+
+ <td>
+ <h3 class="blue">Lorem ipsum</h3>
+ </td>
+ </tr>
+ <tr>
+ <td>
+ <pre><code><h3 class="green">…</h3></code></pre>
+ </td>
+
+ <td>
+ <h3 class="green">Lorem ipsum</h3>
+ </td>
+ </tr>
+ <tr>
+ <td>
+ <pre><code><h3 class="orange">…</h3></code></pre>
+ </td>
+
+ <td>
+ <h3 class="orange">Lorem ipsum</h3>
+ </td>
+ </tr>
+
+ <tr>
+ <td>
+ <pre><code><p class="blue">…</p></code></pre>
+ </td>
+
+ <td>
+ <p class="blue">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
+ </td>
+ </tr>
+ <tr>
+ <td>
+ <pre><code><p class="green">…</p></code></pre>
+ </td>
+
+ <td>
+ <p class="green">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
+ </td>
+ </tr>
+ <tr>
+ <td>
+ <pre><code><p class="orange">…</p></code></pre>
+ </td>
+
+ <td>
+ <p class="orange">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
+ </td>
+ </tr>
+
+ <tr>
+ <td>
+ <pre><code><div class="box"><br /> <div class="wrapper">…</div><br /></div></code></pre>
+ </td>
+
+ <td>
+ <div class="box"><div class="wrapper">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</div></div>
+ </td>
+ </tr>
+
+ <tr>
+ <td>
+ <pre><code><p class="dark">…</p></code></pre>
+ </td>
+
+ <td>
+ <p class="dark">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
+ </td>
+ </tr>
+
+ <tr>
+ <td>
+ <pre><code><p class="light">…</p></code></pre>
+ </td>
+
+ <td>
+ <p class="light">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
+ </td>
+ </tr>
+
+
+
+</table>
diff --git a/views/index.erb b/views/index.erb
new file mode 100644
index 0000000..b705c50
--- /dev/null
+++ b/views/index.erb
@@ -0,0 +1,104 @@
+<div id="sidebar">
+ <h3>Where to start</h3>
+ <h4>Check out the <code style="font-size: 140%">dashboard_controller</code></h4>
+
+ <p class="description">
+ The controller in this demo application fetches the latest 3 orders and products and makes them available as instance variables <code style="color: #218BCE">@orders</code> and <code style="color: #218BCE">@products</code>.
+ </p>
+
+ <h4>Check out the <code>index</code> template</h4>
+
+ <p class="description">
+ This is the Ruby template you are currently looking at. It is located at:<br />
+ </p>
+
+ <p style="background: #fff; margin-left: 4px"><code>views/dashboard/index.html.erb</code></p>
+
+ <p class="description">
+ Have a look at the markup and Ruby code to see how the Shopify API is being used.
+ </p>
+
+ <h3>Additional documentation</h3>
+
+ <p class="description">
+ Become an expert:
+ </p>
+
+ <ul>
+ <li>
+ <a href='http://www.shopify.com/developers/api/'>API documentation</a>
+ <span class="note">The reference: what you can do with the Shopify API.</span>
+ </li>
+ <li>
+ <a href='http://wiki.shopify.com/'>Wiki</a>
+ <span class="note">Get more information and share your knowledge.</span>
+ </li>
+ <li>
+ <a href='http://forums.shopify.com/community'>Forum</a>
+ <span class="note">Ask questions and see what others already wanted to know.</span>
+ </li>
+ </ul>
+
+ <h3>Once you're ready</h3>
+
+ <p class="description">
+ We'd love to see what you create using the Shopify API.
+ Find out how to share your application with the world and read the latest information on the <a href='http://www.shopify.com/developers/publishing/'>API Publishing Page</a>.
+ </p>
+</div>
+
+
+<div id="orders">
+ <h2>Your recent orders</h2>
+
+ <% if @orders.blank? %>
+
+ <em class="note">There are no orders in your store.</em>
+
+ <% else %>
+
+ <ul>
+ <% @orders.each do |order| %>
+ <li>
+ <div class="order box">
+ <div class="wrapper">
+ <strong><a href='<%= "http://#{current_shop.url}/admin/orders/#{order.id}" %>'><%= order.name %></a></strong>
+
+ <span class="price"><%= order.total_price %> <%= order.currency %></span>
+ <span class="highlight"><%= order.financial_status %></span>
+ by <span class="note"><%= order.billing_address.name %></span>
+ </div>
+ </div>
+ </li>
+ <% end %>
+ </ul>
+
+ <% end %>
+</div>
+
+
+<h2>Some of your products</h2>
+
+<% if @products.blank? %>
+
+ <em class="note">There are no products in your store.</em>
+
+<% else %>
+
+ <% @products.each do |product| %>
+ <div class="product box">
+ <div class="wrapper">
+ <img src='<%= product.images.first.small rescue '' %>' />
+
+ <h4><a href='<%= "http://#{current_shop.url}/admin/products/#{product.id}" %>'><%= product.title %></a>
+
+ <p class="price"><%= product.price_range %> <%= current_shop.shop.currency %></p>
+ <p style="margin-bottom: 0"><%= product.product_type %> <span class="note">type</span></p>
+ <p style="margin: 0"><%= product.vendor %> <span class="note">vendor</span></p>
+
+ <div style="clear:left"></div>
+ </div>
+ </div>
+ <% end %>
+
+<% end %>
diff --git a/views/layout.erb b/views/layout.erb
new file mode 100644
index 0000000..b27127d
--- /dev/null
+++ b/views/layout.erb
@@ -0,0 +1,42 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
+<head>
+ <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
+ <meta http-equiv="imagetoolbar" content="no" />
+ <meta name="MSSmartTagsPreventParsing" content="true" />
+
+ <title>Shopify Application</title>
+
+ <link type="text/css" rel="stylesheet" href="/stylesheets/application.css" />
+</head>
+
+<body>
+
+ <div id="header">
+ <h1><a href='/'>Shopify Demo Application</a></h1>
+
+ <p id="login-link">
+ <% if current_shop %>
+ <span class="note">current shop</span> <a class='shop_name' href='http://#{current_shop.url}'><%= current_shop.url %></a><span class="note">|</span>
+ <a href='/logout'>logout</a>
+ <% end %>
+ </p>
+ </div>
+
+ <div id="container" class="clearfix">
+
+ <ul id="tabs">
+ <a href='/home' <%= if request.env['PATH_INFO'] =~ /home/ then "id='current'" end %>>Home</a>
+ <a href='/design' <%= if request.env['PATH_INFO'] =~ /design/ then "id='current'" end %>>Design Help</a>
+ </ul>
+
+ <!-- begin div.main-->
+ <div id="main">
+ <%= yield %>
+ </div>
+ <!-- end div.main -->
+
+ </div>
+
+</body>
+</html>
\ No newline at end of file
|
jstorimer/sinatra-shopify
|
171b0ae7bbbb9dd1f5b035f32860e25c69ad8e90
|
initial
|
diff --git a/app.rb b/app.rb
new file mode 100644
index 0000000..50e2fe0
--- /dev/null
+++ b/app.rb
@@ -0,0 +1,8 @@
+require 'rubygems'
+require 'sinatra'
+require 'sinatra/shopify'
+
+get '/' do
+ authorize!
+ erb :index
+end
\ No newline at end of file
diff --git a/lib/shopify.rb b/lib/shopify.rb
new file mode 100644
index 0000000..046890c
--- /dev/null
+++ b/lib/shopify.rb
@@ -0,0 +1,47 @@
+require 'sinatra/base'
+
+module Sinatra
+ module Shopify
+
+ module Helpers
+ def current_shop
+ session[:shopify]
+ end
+
+ def authorize!
+ redirect '/login' unless current_shop
+ end
+
+ def logout!
+ session[:shopify] = nil
+ end
+ end
+
+ def self.registered(app)
+ app.helpers Shopify::Helpers
+
+ app.get '/login' do
+ erb :login
+ end
+
+ app.post '/login/authenticate' do
+ redirect ShopifyAPI::Session.new(params[:shop]).create_permission_url
+ end
+
+ app.get '/login/finalize' do
+ shopify_session = ShopifyAPI::Session.new(params[:shop], params[:t])
+ if shopify_session.valid?
+ session[:shopify] = shopify_session
+
+ return_address = session[:return_to] || '/'
+ session[:return_to] = nil
+ redirect return_address
+ else
+ redirect '/login'
+ end
+ end
+ end
+ end
+
+ register Shopify
+end
\ No newline at end of file
diff --git a/public/images/box-bg2.gif b/public/images/box-bg2.gif
new file mode 100644
index 0000000..ae537bc
Binary files /dev/null and b/public/images/box-bg2.gif differ
diff --git a/public/images/info-bg.gif b/public/images/info-bg.gif
new file mode 100644
index 0000000..730b5fb
Binary files /dev/null and b/public/images/info-bg.gif differ
diff --git a/public/images/info.gif b/public/images/info.gif
new file mode 100644
index 0000000..efeb456
Binary files /dev/null and b/public/images/info.gif differ
diff --git a/public/images/shopify-logo.png b/public/images/shopify-logo.png
new file mode 100644
index 0000000..81ed3cc
Binary files /dev/null and b/public/images/shopify-logo.png differ
diff --git a/public/stylesheets/application.css b/public/stylesheets/application.css
new file mode 100644
index 0000000..0e05015
--- /dev/null
+++ b/public/stylesheets/application.css
@@ -0,0 +1,285 @@
+body {
+ margin: 0;
+ font: 0.8em/1.3em "Lucida Grande", Arial, Arial, sans-serif;
+ background: #ededed;
+}
+
+h1 { font-weight: normal; font-size: 24px; }
+h1 a { color: #FFFAD5; text-decoration: none; }
+h2 { font-weight: normal; margin-top: 24px; }
+h3 { margin-top: 24px; }
+
+#header {
+ background: #2d3337 url('../images/shopify-logo.png') 20px 50% no-repeat;
+ padding: 25px 25px 25px 70px;
+ border-top: 5px solid #1f2326;
+ border-bottom: 1px solid #252a2e;
+}
+
+#header h1 { color: #fffad5; }
+
+#login-link {
+ float: right;
+ position: relative;
+ bottom: 43px;
+ right: 15px;
+ color: #ededed;
+}
+
+#login-link a { color: #ebff7c; }
+#login-link a:hover { text-decoration: underline; }
+#login-link a.shop_name { color: inherit; text-decoration: none; }
+#login-link a.shop_name:hover { text-decoration: underline; }
+
+#container {
+ width: 90%;
+ min-width: 800px;
+ margin: 40px auto;
+ background: #fff;
+ border-right: 1px solid #e5e5e5;
+ border-bottom: 1px solid #e5e5e5;
+}
+
+#container h1 { margin: 18px 0 27px 0; }
+
+#main { padding: 18px; }
+
+#tabs {
+ margin: 0;
+ padding: 0;
+ height: 20px;
+ position: absolute;
+ top: 123px;
+}
+
+#tabs li {
+ margin: 0;
+ padding: 0;
+ display: inline;
+ list-style-type: none;
+}
+
+#tabs a:link, #tabs a:visited {
+ float: left;
+ padding: 3px 8px ;
+ margin: 0 10px 4px 0px;
+ text-decoration: none;
+ color: #888;
+ background: #ddd;
+}
+
+#tabs a:link#current, #tabs a:visited#current, #tabs a:hover { color: #000 !important; }
+#tabs a:link#current, #tabs a:visited#current { font-weight: bold; background: #fff; }
+
+a { color: #22658b; }
+a:hover { color: #359cd7; }
+
+dl { margin: 10px 15px; }
+dt { margin: 10px 0; }
+dd { margin: 5px 0 15px 0; }
+dl input { margin: 0 !important; }
+
+code { font-size: 140%; }
+
+/* UTILITY CLASSES */
+
+.clearfix:after {
+ content: ".";
+ display: block;
+ height: 0;
+ clear: both;
+ visibility: hidden;
+}
+
+.clearfix {display: inline-table;}
+
+/* Hides from IE-mac \*/
+* html .clearfix {height: 1%;}
+.clearfix {display: block;}
+/* End hide from IE-mac */
+
+.ta-left { text-align: left; }
+.ta-right { text-align: right; }
+.ta-center { text-align: center; }
+.pl { padding-left: 10px !important; }
+.note { color: #777; font-size: 85%; }
+.highlight { background: #ffc; }
+
+/*
+ * LOGIN / WELCOME
+ */
+
+#left, #right {
+ width: 40%;
+ float: left;
+ margin: 0 2% 30px 2%;
+}
+
+#left { min-width: 390px; }
+
+#logout { float: right; margin: 10px; }
+#logout a { color: #330; }
+
+/*
+ * DASHBOARD
+ */
+
+.order, .product { width: 55%; }
+.product { margin: 10px; }
+
+.product img {
+ margin: 0 10px 0 0;
+ float: left;
+}
+
+.product h4 {
+ margin: 0 0 12px 0;
+ font-size: 14px;
+}
+
+.price {
+ color: #666;
+ font-size: 15px;
+ font-family: Times, "Times New Roman";
+ font-style: italic;
+}
+
+#orders ul {
+ list-style-type: none;
+ padding: 0 0 0 7px;
+}
+
+#orders li { padding: 3px; }
+
+#sidebar {
+ float: right;
+ width: 280px;
+ background: #f5fbfe;
+ border-left: 1px solid #D7E4EA;
+ color: #003366;
+ padding: 0 20px 20px 20px;
+ margin-bottom: 18px;
+}
+
+#sidebar ul {
+ padding-left: 20px;
+ list-style-type: square;
+}
+
+#sidebar li { margin: 8px 0; }
+
+/* STYLE OVERVIEW */
+
+#style-table { margin: 20px 0; }
+#style-table td * { margin: 0; }
+#style-table td { padding: 10px; border-bottom: 1px dotted #e5e5e5; }
+#style-table td:first-child {
+ background:#Fefefe url('../images/box-bg2.gif') repeat-x scroll left bottom;
+}
+/* Flash */
+
+#flasherrors, #flashnotices {
+ background: #faf7ea;
+ border-bottom: 1px solid #e8e6d9;
+ padding: 10px;
+ font-weight: bold;
+ text-align:center;
+}
+
+#flasherrors { color: #6e290b; }
+#flashnotices { color: #549d19; }
+
+/* CLASSES */
+
+.description {
+ margin: 0px 0px 0px 4px;
+ font-weight: normal;
+}
+
+.box {
+ padding: 0;
+ background:#FAFAFA url('../images/box-bg2.gif') repeat-x scroll left top;
+ border:1px solid #CCCCCC;
+}
+
+.wrapper {
+ border:1px solid #FFFFFF;
+ padding: 10px;
+}
+
+.info {
+ padding: 0;
+ margin: 8px auto;
+ background: #009ad6 url('../images/info-bg.gif') top left repeat-x;
+ border: 1px solid #61abda;
+ font: 1.2em/1.7em "Comic Sans MS";
+ color: #fff;
+ height: 85px;
+}
+
+.info code {
+ font-size: 14px;
+ background: none;
+}
+
+.info a { color: #fff; }
+.info a:hover { color: #dcfaff; }
+
+.grey {
+ background: #eee;
+ border: 1px solid #ccc;
+}
+
+.green, .orange, .blue { padding: 10px; }
+h1.green, h2.green, h3.green, h1.orange, h2.orange, h3.orange, h1.blue, h2.blue, h3.blue { padding: 0; }
+
+.green {
+ background: #61b41e;
+ border: 1px solid #60b31d;
+ color: #ddecd0;
+}
+
+h1.green, h2.green, h3.green {
+ color: #6ece21;
+ background: none;
+ border: none;
+}
+
+.orange {
+ background: #ce6e21;
+ border: 1px solid #bc641e;
+ color: #fce0ca;
+ padding: 10px;
+}
+
+h1.orange, h2.orange, h3.orange {
+ color: #ce6e21;
+ background: none;
+ border: none;
+}
+
+.blue {
+ background: #218bce;
+ border: 1px solid #1e80be;
+ color: #d9ecf8;
+ padding: 10px;
+}
+
+h1.blue, h2.blue, h3.blue {
+ color: #218bce;
+ background: none;
+ border: none;
+}
+
+.light {
+ background: #faf7ea;
+ border: 1px solid #e8e6d9;
+ padding: 18px;
+}
+
+.dark {
+ background: #333;
+ border: 1px solid #000;
+ color: #fff;
+ padding: 10px;
+}
\ No newline at end of file
diff --git a/shopify_app b/shopify_app
new file mode 160000
index 0000000..6ae8538
--- /dev/null
+++ b/shopify_app
@@ -0,0 +1 @@
+Subproject commit 6ae8538fbf8a28cfea5f67353b11e68e47671604
diff --git a/views/login.erb b/views/login.erb
new file mode 100644
index 0000000..13fadde
--- /dev/null
+++ b/views/login.erb
@@ -0,0 +1,15 @@
+<h1>Login</h1>
+
+<p>
+ First you have to register this app with a shop to allow access to its private admin data.
+</p>
+
+<form action='/login/authenticate' method='post'>
+ <label for='shop'><strong>The URL of the Shop</strong>
+ <span class="hint">(or just the subdomain if it's at myshopify.com)</span>
+ </label>
+ <p>
+ <input type='text' name='shop' />
+ </p>
+ <input type='submit' value='Authenticate' />
+</form>
\ No newline at end of file
|
julians/Text-Visualisation
|
feaea79e4dfeae04df370bc2b3e277792aad15b9
|
initial import
|
diff --git a/Textvisualisierung.pde b/Textvisualisierung.pde
new file mode 100644
index 0000000..b7e0242
--- /dev/null
+++ b/Textvisualisierung.pde
@@ -0,0 +1,499 @@
+// different fonts
+//
+
+//import processing.pdf.*;
+import rita.wordnet.*;
+
+RiWordnet wordnet;
+
+String content = "";
+HashMap chars;
+PGraphics tp;
+PImage ti;
+HashMap blacknesses;
+ArrayList uniqueChars;
+String[] words;
+int[][] wordProperties;
+HashMap typeForWord;
+
+int currentWord = 0;
+int currentChar = 0;
+int totalLines = 0;
+
+float[][] maps = new float[6][2];
+
+// prefs
+String[] reversed = {"RATIO", "TOTALPIXELS", "BLACKPIXELS", "CHARWIDTH", "CHARHEIGHT", "OFF"};
+
+int RATIO = 0;
+int TOTALPIXELS = 1;
+int BLACKPIXELS = 2;
+int CHARWIDTH = 3;
+int CHARHEIGHT = 4;
+int WORD = 0;
+int WORDTYPE = 1;
+int MIN = 0;
+int MAX = 1;
+int OFF = 5;
+int VERB = 0;
+int ADVERB = 1;
+int ADJECTIVE = 2;
+int NOUN = 3;
+int OTHER = 4;
+int WHITESPACE = 5;
+int PUNCTUATION = 6;
+int OFFCOLOUR = 7;
+
+int charsPerLine = 60;
+int linesPerPage = 30;
+int pY = OFF;
+int pA = OFF;
+int pC = OFF;
+boolean drawText = false;
+boolean drawAll = true;
+
+int[] colours = new int[8];
+
+// temp vars for draw method
+int tx = 0;
+int ty = 0;
+String ts = "";
+
+PImage bg;
+
+int[] buttons;
+
+void setup ()
+{
+ size(1024, 768);
+ smooth();
+ colorMode(HSB, 360, 100, 100, 100);
+ frameRate(60);
+ bg = loadImage("background.png");
+
+ colours[VERB] = color(50, 98, 95); //yellow
+ colours[ADVERB] = color(197, 98, 55); //blue
+ colours[ADJECTIVE] = color(186, 98, 75); //light blue
+ colours[NOUN] = color(355, 88, 95); //red
+ colours[OTHER] = color(0, 0, 35); //dark grey
+ colours[WHITESPACE] = color(0, 0, 70); //light grey
+ colours[PUNCTUATION] = color(78, 86, 78); //green
+ colours[OFFCOLOUR] = color(0, 0, 0); //black
+
+ buttons = new int[height];
+ for (int i = 0; i < buttons.length; i++) {
+ buttons[i] = -1;
+ }
+ fillButton(47, RATIO);
+ fillButton(68, TOTALPIXELS);
+ fillButton(89, BLACKPIXELS);
+ fillButton(110, CHARWIDTH);
+ fillButton(131, CHARHEIGHT);
+ fillButton(152, OFF);
+
+ fillButton(223, RATIO);
+ fillButton(244, TOTALPIXELS);
+ fillButton(265, BLACKPIXELS);
+ fillButton(286, CHARWIDTH);
+ fillButton(307, CHARHEIGHT);
+ fillButton(328, OFF);
+
+ fillButton(399, WORDTYPE);
+ fillButton(420, OFF);
+
+ Locale.setDefault(Locale.ENGLISH);
+ wordnet = new RiWordnet(this);
+
+ chars = new HashMap(100);
+ typeForWord = new HashMap();
+ blacknesses = new HashMap(100);
+ uniqueChars = new ArrayList(100);
+
+ typeForWord.put("Buckminster", NOUN);
+
+ analyseFile();
+
+ /*
+ Iterator i = blacknesses.entrySet().iterator(); // Get an iterator
+ while (i.hasNext()) {
+ Map.Entry me = (Map.Entry)i.next();
+ print(me.getKey() + " is ");
+ println(me.getValue());
+ }
+ */
+
+ background(0, 0, 93);
+ textFont(createFont("Courier", 14));
+ updateUberList(charsPerLine*linesPerPage);
+}
+
+void analyseFile ()
+{
+ String lines[] = loadStrings("text.txt");
+ StringBuilder result = new StringBuilder();
+ for (int i = 0; i < lines.length; i++) {
+ result.append(lines[i]);
+ result.append("\n");
+ }
+ content = result.toString();
+
+ content = content.replaceAll("\\W+", " ");
+ words = content.split(" ");
+
+ char temp;
+ for (int i = 0; i < content.length(); i++) {
+ temp = content.charAt(i);
+ if (chars.containsKey(temp)) {
+ // this is shit
+ int val = ((Integer) chars.get(temp)) + 1;
+ chars.put(temp, val);
+ } else {
+ chars.put(temp, 1);
+ }
+ }
+ totalLines = floor(content.length()/charsPerLine);
+
+ uniqueChars.addAll(chars.keySet());
+ //Collections.sort(uniqueChars);
+
+ wordProperties = new int[content.length()][7];
+
+ tp = createGraphics(128, 128, P2D);
+ tp.beginDraw();
+ tp.textFont(createFont("Courier", 64));
+ tp.fill(0);
+ tp.noStroke();
+ tp.background(255);
+ tp.textAlign(CENTER);
+ tp.endDraw();
+
+ int a = 0;
+ int r = 0;
+ int g = 0;
+ int b = 0;
+ int x = 0;
+ int y = 0;
+ int argb = 0;
+ int minX = 128;
+ int minY = 128;
+ int maxX = 0;
+ int maxY = 0;
+ float charWidth = 0;
+ float charHeight = 0;
+ float blacks = 0;
+
+ for (int j = 0; j < uniqueChars.size(); j++) {
+ if (uniqueChars.get(j).toString().contentEquals(" ")) {
+ float[] data = {0, 0, 0, 0, 0};
+ blacknesses.put(uniqueChars.get(j), data);
+ continue;
+ }
+ tp.beginDraw();
+ tp.background(255);
+ tp.text(uniqueChars.get(j).toString(), 64, 64);
+ tp.endDraw();
+ tp.loadPixels();
+
+ minX = 128;
+ minY = 128;
+ maxX = 0;
+ maxY = 0;
+ charWidth = 0;
+ charHeight = 0;
+ blacks = 0;
+ for (int i = 0; i < tp.pixels.length; i++) {
+ argb = tp.pixels[i];
+ if (argb != -1) {
+ a = (argb >> 24) & 0xFF;
+ r = (argb >> 16) & 0xFF; // Faster way of getting red(argb)
+ g = (argb >> 8) & 0xFF; // Faster way of getting green(argb)
+ b = argb & 0xFF; // Faster way of getting blue(argb)
+
+ x = i%128;
+ y = (i - (i%128))/128;
+ if (x < minX) minX = x;
+ if (y < minY) minY = y;
+ if (x > maxX) maxX = x;
+ if (y > maxY) maxY = y;
+
+ a = (argb >> 24) & 0xFF;
+ r = (argb >> 16) & 0xFF; // Faster way of getting red(argb)
+ g = (argb >> 8) & 0xFF; // Faster way of getting green(argb)
+ b = argb & 0xFF; // Faster way of getting blue(argb)
+
+ if (r < 127 && g < 127 && b < 127) blacks++;
+ }
+ }
+ charWidth = maxX - minX;
+ charHeight = maxY - minY;
+
+ if (maps[CHARWIDTH][MIN] > charWidth) maps[CHARWIDTH][MIN] = charWidth;
+ if (maps[CHARWIDTH][MAX] < charWidth) maps[CHARWIDTH][MAX] = charWidth;
+
+ if (maps[CHARHEIGHT][MIN] > charHeight) maps[CHARHEIGHT][MIN] = charHeight;
+ if (maps[CHARHEIGHT][MAX] < charHeight) maps[CHARHEIGHT][MAX] = charHeight;
+
+ if (maps[BLACKPIXELS][MIN] > blacks) maps[BLACKPIXELS][MIN] = blacks;
+ if (maps[BLACKPIXELS][MAX] < blacks) maps[BLACKPIXELS][MAX] = blacks;
+
+ if (maps[TOTALPIXELS][MIN] > charWidth*charHeight) maps[TOTALPIXELS][MIN] = charWidth*charHeight;
+ if (maps[TOTALPIXELS][MAX] < charWidth*charHeight) maps[TOTALPIXELS][MAX] = charWidth*charHeight;
+
+ float[] data = {blacks/(charWidth*charHeight), charWidth*charHeight, blacks, charWidth, charHeight};
+ blacknesses.put(uniqueChars.get(j), data);
+ }
+
+ maps[RATIO][MIN] = 0;
+ maps[RATIO][MAX] = 1;
+}
+
+void draw ()
+{
+ if (drawAll) {
+ background(0, 0, 93);
+ image(bg, 0, 0);
+ translate(232, 20);
+ fill(0, 0, 100);
+ noStroke();
+ rect(0, 0, 560, 700);
+ noFill();
+ stroke(0, 0, 85);
+ line(0, 700, 560, 700);
+ if (drawText) drawText(24);
+ drawAbstract();
+ resetMatrix();
+
+ fill(0, 40);
+ noStroke();
+ for (int i = 390; i < 500; i++) {
+ if (buttons[i] == pC) {
+ rect(860, i+2, 7, 7);
+ break;
+ }
+ }
+ for (int i = 220; i < 380; i++) {
+ if (buttons[i] == pA) {
+ rect(860, i+2, 7, 7);
+ break;
+ }
+ }
+ for (int i = 40; i < 210; i++) {
+ if (buttons[i] == pY) {
+ rect(860, i+2, 7, 7);
+ break;
+ }
+ }
+ if (drawText) rect(860, 493, 7, 7);
+
+ drawAll = false;
+ }
+ fill(0, 0, 93);
+ noStroke();
+ rect(0, 0, 200, 200);
+ if (drawAll || (mouseX > 272 && mouseX < 752 && mouseY > 60 - (600/linesPerPage) && mouseY < 60 - (600/linesPerPage) + 600)) {
+ ts = "";
+ tx = mouseX - 272;
+ ty = mouseY - (60 - (600/linesPerPage));
+ tx = floor(tx/8);
+ ty = floor(ty/(600/linesPerPage));
+
+ if (wordProperties[tx+(ty*charsPerLine)][WORD] >= 0) {
+ fill(colours[wordProperties[tx+(ty*charsPerLine)][WORDTYPE]]);
+ text(words[wordProperties[tx+(ty*charsPerLine)][WORD]], 40, 60);
+ }
+
+ fill(0, 24);
+ text(content.charAt(tx+(ty*charsPerLine)), 40, 80);
+ text("Zeile " + ty, 40, 100);
+ text("Buchstabe " + tx, 40, 120);
+ }
+}
+
+void fillButton (int start, int value)
+{
+ for (int i = start; i < start + 11; i++) {
+ buttons[i] = value;
+ }
+}
+
+void mouseClicked ()
+{
+ if (mouseX > 857 && mouseX < 870) {
+ println(mouseY);
+ if (mouseY > 532 && mouseY < 545) {
+ if (linesPerPage > 1) {
+ linesPerPage--;
+ while (600%linesPerPage != 0) {
+ linesPerPage--;
+ }
+ drawAll = true;
+ }
+ } else if (mouseY > 511 && mouseY < 524) {
+ if (linesPerPage < 600) {
+ linesPerPage++;
+ while (600%linesPerPage != 0) {
+ linesPerPage++;
+ }
+ drawAll = true;
+ }
+ } else if (mouseY > 490 && mouseY < 503) {
+ drawText = !drawText;
+ drawAll = true;
+ } else if (mouseY > 390 && buttons[mouseY] > -1) {
+ pC = buttons[mouseY];
+ drawAll = true;
+ } else if (mouseY > 220 && buttons[mouseY] > -1) {
+ pA = buttons[mouseY];
+ drawAll = true;
+ } else if (mouseY > 40 && buttons[mouseY] > -1) {
+ pY = buttons[mouseY];
+ drawAll = true;
+ }
+ }
+}
+
+void keyPressed ()
+{
+ println("----------------------");
+ switch (key) {
+ case 't':
+ drawText = !drawText;
+ break;
+ case '+':
+ if (linesPerPage < 600) {
+ linesPerPage++;
+ while (600%linesPerPage != 0) {
+ linesPerPage++;
+ }
+ }
+ println("lines per page: " + linesPerPage);
+ break;
+ case '-':
+ if (linesPerPage > 1) {
+ linesPerPage--;
+ while (600%linesPerPage != 0) {
+ linesPerPage--;
+ }
+ }
+ println("lines per page: " + linesPerPage);
+ break;
+ case 'c':
+ pC = pC == WORDTYPE ? OFF : WORDTYPE;
+ println("colour off");
+ break;
+ }
+ if (key == CODED) {
+ switch (keyCode) {
+ case RIGHT:
+ pA++;
+ if (pA > 5) pA = 0;
+ println("pA: " + reversed[pA]);
+ break;
+ case LEFT:
+ pA--;
+ if (pA < 0) pA = 5;
+ println("pA: " + reversed[pA]);
+ break;
+ case DOWN:
+ pY++;
+ if (pY > 5) pY = 0;
+ println("pY: " + reversed[pY]);
+ break;
+ case UP:
+ pY--;
+ if (pY < 0) pY = 5;
+ println("pY: " + reversed[pY]);
+ break;
+ }
+ }
+ drawAll = true;
+}
+
+void drawAbstract ()
+{
+ float [] ftemp;
+ PVector lastPoint = new PVector(0, 0);
+ PVector thisPoint = new PVector(0, 0);
+ noFill();
+ strokeWeight(1);
+
+ color c;
+ float a;
+ float y;
+
+ int in;
+ float [] fl;
+
+ updateUberList(charsPerLine*linesPerPage);
+ for (int k = 0; k < linesPerPage; k++) {
+ for (int j = 0; j < charsPerLine; j++) {
+ in = charsPerLine*k+j;
+ fl = (float[]) blacknesses.get(content.charAt(in));
+
+ if (thisPoint.x != 0 && thisPoint.y != 0) lastPoint.set(thisPoint.x, thisPoint.y, 0);
+
+ a = pA == OFF ? 100 : map(fl[pA], maps[pA][MIN], maps[pA][MAX], 10, 100);
+ y = pY == OFF ? 0 : map(fl[pY], maps[pY][MIN], maps[pY][MAX], 0, 12);
+ c = pC == OFF ? OFFCOLOUR : wordProperties[in][WORDTYPE];
+ stroke(colours[c], a);
+ thisPoint.set(40+(j*8)+4, k*(600/linesPerPage)+40-y, 0);
+
+ if (j > 1) {
+ line(lastPoint.x+1, lastPoint.y, thisPoint.x, thisPoint.y);
+ } else if (j == 1) {
+ line(lastPoint.x, lastPoint.y, thisPoint.x, thisPoint.y);
+ }
+ }
+ }
+}
+
+void drawText (float tAlpha)
+{
+ fill(0, tAlpha);
+ for (int k = 0; k < linesPerPage; k++) {
+ StringBuilder l = new StringBuilder();
+ for (int j = 0; j < charsPerLine; j++) {
+ l.append(content.charAt(charsPerLine*k+j));
+ }
+ text(l.toString(), 40, k*(600/linesPerPage)+40);
+ }
+}
+
+void updateUberList (int num)
+{
+ if (num > currentChar) {
+ char tc;
+ for (int i = currentChar; i < num; i++) {
+ tc = content.charAt(i);
+ if (Character.isLetter(tc) || Character.isDigit(tc)) {
+ wordProperties[i][WORD] = currentWord;
+
+ if (typeForWord.containsKey(currentWord)) {
+ wordProperties[i][WORDTYPE] = (Integer) typeForWord.get(currentWord);
+ } else {
+ if (wordnet.isVerb(words[currentWord])) {
+ wordProperties[i][WORDTYPE] = VERB;
+ } else if (wordnet.isAdverb(words[currentWord])) {
+ wordProperties[i][WORDTYPE] = ADVERB;
+ } else if (wordnet.isAdjective(words[currentWord])) {
+ wordProperties[i][WORDTYPE] = ADJECTIVE;
+ } else if (wordnet.isNoun(words[currentWord])) {
+ wordProperties[i][WORDTYPE] = NOUN;
+ } else {
+ wordProperties[i][WORDTYPE] = OTHER;
+ }
+ typeForWord.put(currentWord, wordProperties[i][WORDTYPE]);
+ }
+ } else if (Character.isWhitespace(tc)) {
+ wordProperties[i][WORDTYPE] = WHITESPACE;
+ wordProperties[i][WORD] = -2;
+ if (i > 0 && wordProperties[i-1][WORD] != -2) currentWord += 1;
+ } else {
+ wordProperties[i][WORDTYPE] = PUNCTUATION;
+ wordProperties[i][WORD] = -1;
+ currentWord += 1;
+ }
+ }
+ currentChar = num;
+ }
+}
\ No newline at end of file
diff --git a/data/background.png b/data/background.png
new file mode 100644
index 0000000..0d6de62
Binary files /dev/null and b/data/background.png differ
diff --git a/data/text.txt b/data/text.txt
new file mode 100644
index 0000000..aafedf9
--- /dev/null
+++ b/data/text.txt
@@ -0,0 +1,408 @@
+Operating Manual for Spaceship Earth
+
+By R. Buckminster Fuller
+
+1. comprehensive propensities
+
+I am enthusiastic over humanityâs extraordinary and sometimes very timely ingenuities. If you are in a shipwreck and all the boats are gone, a piano top buoyant enough to keep you afloat that comes along makes a fortuitous life preserver. But this is not to say that the best way to design a life preserver is in the form of a piano top. I think that we are clinging to a great many piano tops in accepting yesterdayâs fortuitous contrivings as constituting the only means for solving a given problem. Our brains deal exclusively with special-case experiences. Only our minds are able to discover the generalized principles operating without exception in each and every special-experience case which if detected and mastered will give knowledgeable advantage in all instances.
+
+Because our spontaneous initiative has been frustrated, too often inadvertently, in earliest childhood we do not tend, customarily, to dare to think competently regarding our potentials. We find it socially easier to go on with our narrow, shortsighted specializationâs and leave it to othersâprimarily to the politiciansâto find some way of resolving our common dilemmas. Countering that spontaneous grownup trend to narrowness I will do my, hopefully "childish," best to confront as many of our problems as possible by employing the longest-distance thinking of which I am capableâthough that may not take us very far into the future.
+
+Having been trained at the U. S. Naval Academy and practically experienced in the powerfully effective forecasting arts of celestial navigation, pilotage, ballistics, and logistics, and in the long-range, anticipatory, design science governing yesterdayâs naval mastery of the world from which our present dayâs general systems theory has been derived, I recall that in 1927 I set about deliberately exploring to see how far ahead we could make competent forecasts regarding the direction in which all humanity is trending and to see how effectively we could interpret the physical details of what comprehensive evolution might be portending as disclosed by the available data. I came to the conclusion that it is possible to make a fairly reasonable forecast of about twenty-five years. That seems to be about one industrial "tooling" generation. On the average, all inventions seem to get melted up about every twenty-five years, after which the metals come back into recirculation in new and usually more effective uses. At any rate, in 1927 I evolved a forecast. Most of my 1927âS prognosticating went only to 1952âthat is, for a quarter-century, but some of it went on for a half-century, to 1977.
+
+In 1927 when people had occasion to ask me about my prognostications and I told them what I thought it would be appropriate to do about what I could see ahead for the 1950âS, 1960âS, and 1970âs people used to say to me, "Very amusingâyou are a thousand years ahead of your time." Having myself studied the increments in which we can think forwardly I was amazed at the ease with which the rest of society seemed to be able to see a thousand years ahead while I could see only one-fortieth of that time distance. As time went on people began to tell me that I was a hundred years ahead, and now they tell me that Iâm a little behind the times. But I have learned about public reaction to the unfamiliar and also about the ease and speed with which the transformed reality becomes so "natural" as misseemingly to have been always obvious. So I knew that their last observations were made only because the evolutionary events I had foreseen have occurred on schedule.
+
+However, all that experience gives me confidence in discussing the next quarter-centuryâs events. First, Iâd like to explore a few thoughts about the vital data confronting us right now-such as the fact that more than half of humanity as yet exists in miserable poverty, prematurely doomed, unless we alter our comprehensive physical circumstances. It is certainly no solution to evict the poor, replacing their squalid housing with much more expensive buildings which the original tenants canât afford to reoccupy. Our society adopts many such superficial palliatives. Because yesterdayâs negatives are moved out of sight from their familiar locations many persons are willing to pretend to themselves that the problems have been solved. I feel that one of the reasons why we are struggling inadequately today is that we reckon our costs on too shortsighted a basis and are later overwhelmed with the unexpected costs brought about by our shortsightedness.
+
+Of course, our failures are a consequence of many factors, but possibly one of the most important is the fact that society operates on the theory that specialization is the key to success, not realizing that specialization precludes comprehensive thinking. This means that the potentially-integratable-techno-economic advantages accruing to society from the myriad specializations are not comprehended integratively and therefore are not realized, or they are realized only in negative ways, in new weaponry or the industrial support only of warfaring.
+
+All universities have been progressively organized for ever finer specialization. Society assumes that specialization is natural, inevitable, and desirable. Yet in observing a little child, we find it is interested in everything and spontaneously apprehends, comprehends, and co-ordinates an ever expending inventory of experiences. Children are enthusiastic planetarium audiences. Nothing seems to be more prominent about human life than its wanting to understand all and put everything together.
+
+One of humanityâs prime drives is to understand and be understood. All other living creatures are designed for highly specialized tasks. Man seems unique as the comprehensive comprehender and co-ordinator of local universe affairs. If the total scheme of nature required man to be a specialist she would have made him so by having him born with one eye and a microscope attached to it.
+
+What nature needed man to be was adaptive in many if not any direction; wherefore she gave man a mind as well as a coordinating switchboard brain. Mind apprehends and comprehends the general principles governing flight and deep sea diving, and man puts on his wings or his lungs, then takes them off when not using them. The specialist bird is greatly impeded by its wings when trying to walk. The fish cannot come out of the sea and walk upon land, for birds and fish are specialists.
+
+Of course, we are beginning to learn a little in the behavioral sciences regarding how little we know about children and the educational processes. We had assumed the child to be an empty brain receptacle into which we could inject our methodically-gained wisdom until that child, too, became educated. In the light of modern behavioral science experiments that was not a good working assumption.
+
+Inasmuch as the new life always manifests comprehensive propensities I would like to know why it is that we have disregarded all childrenâs significantly spontaneous and comprehensive curiosity and in our formal education have deliberately instituted processes leading only to narrow specialization. We do not have to go very far back in history for the answer. We get back to great, powerful men of the sword, exploiting their prowess fortuitously and ambitiously, surrounded by the abysmal ignorance of world society. We find early society struggling under economic conditions wherein less than I per cent of humanity seemed able to live its full span of years. This forlorn economic prospect resulted from the seeming inadequacy of vital resources and from an illiterate societyâs inability to cope successfully with the environment, while saddled also with preconditioned instincts which inadvertently produced many new human babies. Amongst the strugglers we had cunning leaders who said, "Follow me, and weâll make out better than the others." It was the most powerful and shrewd of these leaders who, as we shall see, invented and developed specialization.
+
+Looking at the total historical pattern of man around the Earth and observing that three quarters of the Earth is water, it seems obvious why men, unaware that they would some day contrive to fly and penetrate the ocean in submarines, thought of themselves exclusively as pedestriansâas dry land specialists. Confined to the quarter of the Earthâs surface which is dry land it is easy to see how they came to specialize further as farmers or hunters-or, commanded by their leader, became specialized as soldiers. Less than half of the dry 25 per cent of the Earthâs surface was immediately favorable to the support of human life. Thus, throughout history 99.9 per cent of humanity has occupied only 10 per cent of the total Earth surface, dwelling only where life support was visibly obvious. The favorable land was not in one piece, but consisted of a myriad of relatively small parcels widely dispersed over the surface of the enormous Earth sphere. The small isolated groups of humanity were utterly unaware of one anotherâs existence. They were everywhere ignorant of the vast variety of very different environments and resource patterns occurring other than where they dwelt.
+
+But there were a few human beings who gradually, through the process of invention and experiment, built and operated, first, local river and bay, next, along-shore, then off-shore rafts, dugouts, grass boats, and outrigger sailing canoes. Finally, they developed voluminous rib-bellied fishing vessels, and thereby ventured out to sea for progressively longer periods. Developing ever larger and more capable ships, the seafarers eventually were able to remain for months on the high seas. Thus, these venturers came to live normally at sea. This led them inevitably into world-around, swift, fortune-producing enterprise. Thus they became the first world men.
+
+The men who were able to establish themselves on the oceans had also to be extraordinarily effective with the sword upon both land and sea. They had also to have great anticipatory vision, great ship designing capability, and original scientific conceptioning, mathematical skill in navigation and exploration techniques for coping in fog, night, and storm with the invisible hazards of rocks, shoals, and currents. The great sea venturers had to be able to command all the people in their dry land realm in order to commandeer the adequate metalworking, woodworking, weaving, and other skills necessary to produce their large, complex ships. They had to establish and maintain their authority in order that they themselves and the craftsmen preoccupied in producing the ship be adequately fed by the food-producing hunters and farmers of their realm. Here we see the specialization being greatly amplified under the supreme authority of the comprehensively visionary and brilliantly co-ordinated top swordsman, sea venturer. If his "ship came in"âthat is, returned safely from its yearsâ long venturingâall the people in his realm prospered and their leaderâs power was vastly amplified.
+
+There were very few of these top power men. But as they went on their sea ventures they gradually found that the waters interconnected all the worldâs people and lands. They learned this unbeknownst to their illiterate sailors, who, often as not, having been hit over the head in a saloon and dragged aboard to wake up at sea, saw only a lot of water and, without navigational knowledge, had no idea where they had traveled.
+
+The sea masters soon found that the people in each of the different places visited knew nothing of people in other places. The great venturers found the resources of Earth very unevenly distributed, and discovered that by bringing together various resources occurring remotely from one another one complemented the other in producing tools, services, and consumables of high advantage and value. Thus resources in one place which previously had seemed to be absolutely worthless suddenly became highly valued. Enormous wealth was generated by what the sea venturers could do in the way of integrating resources and distributing the products to the, everywhere around the world, amazed and eager customers. The ship owning captains found that they could carry fantastically large cargoes in their ships, due to natureâs floatability-cargoes so large they could not possibly be carried on the backs of animals or the backs of men. Furthermore, the ships could sail across a bay or sea, traveling shorter distances in much less time than it took to go around the shores and over the intervening mountains. So these very few masters of the water world became incalculably rich and powerful.
+
+To understand the development of intellectual specialization, which is our first objective, we must study further the comprehensive intellectual capabilities of the sea leaders in contradistinction to the myriad of physical, muscle, and craft-skill specializations which their intellect and their skillful swordplay commanded. The great sea venturers thought always in terms of the world, because the worldâs waters are continuous and cover three-quarters of the Earth planet. This meant that before the invention and use of cables and wireless 99.9 per cent of humanity thought only in the terms of their own local terrain. Despite our recently developed communications intimacy and popular awareness of total Earth we, too, in 1969 are as yet politically organized entirely in the terms of exclusive and utterly obsolete sovereign separateness.
+
+This "sovereign"âmeaning top-weapons enforcedâ"national" claim upon humans born in various lands leads to ever more severely specialized servitude and highly personalized identity classification. As a consequence of the slavish "categoryitis" the scientifically illogical, and as we shall see, often meaningless questions "Where do you live?" "What are you?" "What religion?" "What race?" â"What nationality?" are all thought of today as logical questions. By the twenty-first century it either will have become evident to humanity that these questions are absurd and anti-evolutionary or men will no longer be living on Earth. If you donât comprehend why that is so, listen to me closely.
+
+2. origins of specialization
+
+Obviously we need to pursue further the origins of specialization into deep history, hoping thereby to correct or eliminate our erroneous concepts. Historically we can say that average human beings throughout pre-twentieth-century history had each seen only about one-millionth of the surface of their spherical Earth. This limited experience gave humans a locally-focused, specialized viewpoint. Not surprisingly, humanity thought the world was flat, and not surprisingly humans thought its horizontally extended plane went circularly outward to infinity. In our schools today we still start off the education of our children by giving them planes and lines that go on, incomprehensibly "forever" toward a meaningless infinity. Such oversimplified viewpoints are misleading, blinding, and debilitating, because they preclude possible discovery of the significance of our integrated experiences.
+
+Under these everyday, knowledge-thwarting or limiting circumstances of humanity, the comprehensively-informed master venturers of history who went to sea soon realized that the only real competition they had was that of other powerful outlaws who might also know or hope to learn through experience "what it is all about." I call these sea mastering people the great outlaws or Great Pirates-the G. P.âsâsimply because the arbitrary laws enacted or edicted by men on the land could not be extended effectively to control humans beyond their shores and out upon the seas. So the world men who lived on the seas were inherently outlaws, and the only laws that could and did rule them were the natural laws-the physical laws of universe which when tempestuous were often cruelly devastating. High seas combined with natureâs fog and night-hidden rocks were uncompromising.
+
+And it followed that these Great Pirates came into mortal battle with one another to see
+who was going to control the vast sea routes and eventually the world. Their battles took place out of sight of landed humanity. Most of the losers went to the bottom utterly unbeknownst to historians. Those who stayed on the top of the waters and prospered did so because of their comprehensive capability. That is they were the antithesis of specialists. They had high proficiency in dealing with celestial navigation, the storms, the sea, the men, the ship, economics, biology, geography, history, and science. The wider and more long distanced their anticipatory strategy, the more successful they became.
+
+But these hard, powerful, brilliantly resourceful sea masters had to sleep occasionally, and therefore found it necessary to surround themselves with super-loyal, muscular but dull-brained illiterates who could not see nor savvy their mastersâ stratagems. There was great safety in the mental dullness of these henchmen. The Great Pirates realized that the only people who could possibly contrive to displace them were the truly bright people. For this reason their number-one strategy was secrecy. If the other powerful pirates did not know where you were going, nor when you had gone, nor when you were coming back, they would not know how to waylay you. If anyone knew when you were coming home, "small-timers" could come out in small boats and waylay you in the dark and take you over-just before you got home tiredly after a two-year treasure-harvesting voyage. Thus hijacking and second-rate piracy became a popular activity around the worldâs shores and harbors. Thus secrecy became the essence of the lives of the successful pirates; ergo, how little is known today of that which I am relating.
+
+Leonardo da Vinci is the outstanding example of the comprehensively anticipatory design scientist. Operating under the patronage of the Duke of Milan he designed the fortified defenses and weaponry as well as the tools of peaceful production. Many other great military powers had their comprehensive design scientist-artist inventors; Michelangelo was one of them.
+
+Many persons wonder why we do not have such men today. It is a mistake to think we cannot. What happened at the time of Leonardo and Galileo was that mathematics was so improved by the advent of the zero that not only was much more scientific shipbuilding made possible but also much more reliable navigation. Immediately thereafter truly large-scale venturing on the worldâs oceans commenced, and the strong sword-leader patrons as admirals put their Leonardos to work, first in designing their new and more powerful world-girdling ships. Next they took their Leonardos to sea with them as their seagoing Merlins to invent ever more powerful tools and strategies on a world-around basis to implement their great campaigns to best all the other great pirates, thereby enabling them to become masters of the world and of all its people and wealth. The required and scientifically designed secrecy of the sea operations thus pulled a curtain that hid the Leonardos from public view, popular ken, and recorded history.
+
+Finally, the sea-dwelling Leonardos became Captains of the ships or even Admirals of Fleets, or Commandants of the Navy yards where they designed and built the fleets, or they became the commandants of the naval war colleges where they designed and developed the comprehensive strategy for running the world for a century to come. This included not only the designing of the network of world-around voyaging and of the ships for each task but also the designing of the industrial establishments and world-around mining operations and naval base-building for production and maintenance of the ships. This Leonardo-type planning inaugurated todayâs large-scale, world-around industrializationâs vast scale of thinking. When the Great Pirates came to building steel steamships and blast furnaces and railroad tracks to handle the logistics, the Leonardos appeared momentarily again in such men as Telford who built the railroads, tunnels, and bridges of England, as well as the first great steamship.
+
+You may say, "Arenât you talking about the British Empire?" I answer, No The so-called British Empire was a manifest of the world-around misconception of who ran things and a disclosure of the popular ignorance of the Great Piratesâ absolute world-controlling through their local-stooge sovereigns and their prime ministers, as only innocuously and locally modified here and there by the separate sovereigntiesâ internal democratic processes. As we soon shall see, the British Isles lying off the coast of Europe constituted in effect a fleet of unsinkable ships and naval bases commanding all the great harbours of Europe. Those islands were the possession of the topmost Pirates. Since the Great Pirates were building, maintaining, supplying their ships on those islands, they also logically made up their crews out of the native islanders who were simply seized or commanded aboard by imperial edict. Seeing these British Islanders aboard the top pirate ships the people around the world mistakenly assumed that the world conquest by the Great Pirates was a conquest by the will, ambition, and organization of the British people. Thus was the G. P.âs grand deception victorious. But the people of those islands never had the ambition to go out and conquer the world. As a people they were manipulated by the top pirates and learned to cheer as they were told of their nationâs world prowess.
+
+The topmost Great Piratesâ Leonardos discoveredâboth in their careful, long-distance
+planning and in their anticipatory inventingâthat the grand strategies of sea power made it experimentally clear that a plurality of ships could usually outmaneuver one ship. So the Great Piratesâ Leonardos invented navies. Then, of course, they had to control various resource-supplying mines, forests, and lands with which and upon which to build the ships and establish the industries essential to building, supplying, and maintaining their navyâs ships.
+
+Then came the grand strategy which said, "divide and conquer." You divide up the other manâs ships in battle or you best him when several of his ships are hauled out on the land
+for repairs. They also had a grand strategy of anticipatory divide and conquer. Anticipatory
+divide and conquer was much more effective than tardy divide and conquer, since it enabled
+those who employed it to surprise the other pirate under conditions unfavorable to the latter, So the great top pirates of the world, realizing that dull people were innocuous and that the only people who could contrive to displace the supreme pirates were the bright ones, set about to apply their grand strategy of anticipatory divide and conquer to solve that situation comprehensively.
+
+The Great Pirate came into each of the various lands where he either acquired or sold goods profitably and picked the strongest man there to be his local head man. The Pirateâs picked man became the Pirateâs general manager of the local realm. If the Great Pirateâs local strong man in a given land had not already done so, the Great Pirate told him to proclaim himself king. Despite the local head manâs secret subservience to him, the Great Pirate allowed and counted upon his king-stooge to convince his countrymen that he, the local king, was indeed the head man of all menâthe god-ordained ruler. To guarantee that sovereign claim the Pirates gave their stooge-kings secret lines of supplies which provided everything required to enforce the sovereign claim. The more massively bejeweled the kings gold crown, and the more visible his court and castle, the less visible was his pirate master.
+
+The Great Pirates said to all their lieutenants around the world, "Any time bright young people show up, Iâd like to know about it, because we need bright men." So each time the Pirate came into port the local king-ruler would mention that he had some bright, young men whose capabilities and thinking shone out in the community. The Great Pirate would say to the king, "All right, you summon them and deal with them as follows: As each young man is brought forward you say to him, âYoung man, you are very bright. Iâm going to assign you to a great history tutor and in due course if you study well and learn enough Iâm going to make you my Royal Historian, but youâve got to pass many examinations by both your teacher and myself.â" And when the next bright boy was brought before him the King was to say, "Iâm going to make you my Royal Treasurer," and so forth. Then the Pirate said to the king, "You will finally say to all of them: But each of you must mind your own business or off go your heads. Iâm the only one who minds everybodyâs business.â "
+
+And this is the way schools beganâas the royal tutorial schools. You realize, I hope, that I am not being facetious. That is it. This is the beginning of schools and colleges and the beginning of intellectual specialization. Of course, it took great wealth to start schools, to have great teachers, and to house, clothe, feed, and cultivate both teachers and students. Only the Great-Pirate-protected robber-barons and the Pirate-protected and secret intelligence-exploited international religious organizations could afford such scholarship investment. And the development of the bright ones into specialists gave the king very great brain power, and made him and his kingdom the most powerful in the land and thus, secretly and greatly, advantaged his patron Pirate in the world competition with the other Great Pirates.
+
+But specialization is in fact only a fancy form of slavery wherein the "expert" is fooled into accepting his slavery by making him feel that in return he is in a socially and culturally preferred, ergo, highly secure, lifelong position. But only the kingâs son received the Kingdom-wide scope of training.
+
+However, the big thinking in general of a spherical Earth and celestial navigation was retained exclusively by the Great Pirates, in contradistinction to a four-cornered, flat world concept, with empire and kingdom circumscribed knowledge, constricted to only that which could be learned through localized preoccupations. Knowledge of the world and its resources was enjoyed exclusively by the Great Pirates, as were also the arts of navigation, shipbuilding and handling, and of grand logistical strategies and of nationally-undetectable,therefore effectively deceptive, international exchange media and trade balancing tricks by which the top pirate, as (in gamblerâs parlance) "the house," always won.
+
+3. comprehensively commanded automation
+
+Then there came a time, which was World War I, when the most powerful out-pirates challenged the in-pirates with the scientific and technological innovation of an entirely new geometry of thinking. The out-pirates attack went under and above the sea surface and into the invisible realm of electronics and chemical warfaring. Caught off-guard, the in-pirates, in order to save themselves, had to allow their scientists to go to work on their own inscrutable terms. Thus, in saving themselves, the Great Pirates allowed the scientists to plunge their grand, industrial logistics, support strategy into the vast ranges of the electro-magnetic spectrum that were utterly invisible to the pirates.
+
+The pirates until then had ruled the world through their extraordinarily keen senses. They judged things for themselves, and they didnât trust anyone elseâs eyes. They trusted only that which they could personally smell, hear, touch, or see. But the Great Pirates couldnât see what was going on in the vast ranges of the electro-magnetic reality. Technology was going from wire to wireless, from track to trackless, from pipe to pipeless, and from visible structural muscle to the invisible chemical element strengths of metallic alloys and electro-magnetics.
+
+The Great Pirates came out of that first world war unable to cope knowledgeably with what was going on in the advanced scientific frontiers of industry. The pirates delegated inspection to their "troubleshooter" experts, but had to content themselves with relayed second-hand information. This forced them to appraise blindlyâergo, only opinionatedlyâwhether this or that man really knew what he was talking about, for the G. P.âs couldnât judge for themselves. Thus the Great Pirates were no longer the masters. That was the end. The Great Pirates became extinct. But because the G. P.âs had always operated secretly, and because they hoped they were not through, they of course did not announce or allow it to be announced that they were extinct. And because the public had never known of them and had been fooled into thinking of their kingly stooges and local politicians as being in reality the head men, society was and is as yet unaware either that the Great Pirates once ran the world or that they are now utterly extinct.
+
+Though the pirates are extinct, all of our international trade balancing and money ratings, as well as all economic accounting, in both the capitalistic and communistic countries, hold strictly to the rules, value systems, terminology, and concepts established by those Great Pirates. Powerful though many successors to the Great Piratesâ fragmented dominions may be, no one government, religion, or enterprise now holds the worldâs physical or metaphysical initiatives.
+
+The metaphysical initiative, too, has gone into competitive confusion between old religions and more recent political or scientific ideologies. These competitors are already so heavily weighted with physical investments and proprietary expediencies as to vitiate any metaphysical initiative. A new, physically uncompromised, metaphysical initiative of unbiased integrity could unify the world. It could
+and probably will be provided by the utterly impersonal problem solutions of the computers. Only to their superhuman range of calculative capabilities can and may all political, scientific, and religious leaders face-savingly acquiesce.
+
+Abraham Lincolnâs concept of "right triumphing over might" was realized when Einstein as metaphysical intellect wrote the equation of physical universe E = Mc2 and thus comprehended it. Thus the metaphysical took the measure of, and mastered, the physical. That relationship seems by experience to be irreversible. Nothing in our experience suggests that energy could comprehend and write the equation of intellect. That equation is operating inexorably, and the metaphysical is now manifesting its ability to reign over the physical.
+
+This is the essence of human evolution upon Spaceship Earth. If the present planting of humanity upon Spaceship Earth cannot comprehend this inexorable process and discipline itself to serve exclusively that function of metaphysical mastering of the physical it will be discontinued, and its potential mission in universe will be carried on by the metaphysically endowed capabilities of other beings on other spaceship planets of universe.
+
+The Great Pirates did run the world. They were the first and last to do so. They were world men, and they ran the world with ruthless and brilliant pragmatism based on the mis-seemingly "fundamental" information of their scientifically specialized servants. First came their Royal Society scientific servants, with their "Great" Second Law of thermodynamics, whose "entropy" showed that every energy machine kept losing energy and eventually "ran down." In their pre-speed-of-light-measurement misconceptioning of an omnisimultaneous-instant universe"âthat universe, as an energy machine was thought, also to be "running down." And thus the energy wealth and life support were erroneously thought to be in continuous depletion-orginating the misconception of "spending."
+
+Next came Thomas Malthus, professor of political economics of the Great Pirateâs East India Company, who said that man was multiplying himself at a geometrical rate and that food was multiplying only at an arithmetical rate. And lastly, thirty-five years later, came the G. P.âs biological specialist servant, Charles Darwin, who, explaining his theory of animate evolution, said that survival was only for the fittest.
+
+Quite clearly to the Great Pirates it was a scientific fact that not only was there not enough to go around but apparently not enough to go around for even I per cent of humanity to live at a satisfactorily-sustaining standard of living. And because of entropy the inadequacy would always increase. Hence, said the G. P.âs, survival was obviously a cruel and almost hopeless battle. They ran the world on the basis that these Malthusian-Darwinian entropy concepts were absolute scientific laws, for that was what their scientifically respected, intellectual slave specialists had told them.
+
+Then we have the great pragmatic ideologist Marx running into that entropic-Malthusian-Darwinian information and saying, "Well, the workers who produce things are the fittest because they are the only ones who know how to physically produce and therefore they ought to be the ones to survive." That was the beginning of the great "class warfare." All of the ideologies range somewhere between the Great Pirates and the Marxists. But all of them assume that there is not enough to go around. And thatâs been the rationalized working hypothesis of all the great sovereign claims to great areas of the Earth. Because of their respective exclusivities, all the class warfare ideologies have become extinct. Capitalism and socialism are mutually extinct. Why? Because science now finds there can be ample for all, but only if the sovereign fences are completely removed. The basic you-or-me-not-enough-for-bothâergo, someone-must-dieâtenets of the class warfaring are extinct.
+
+Now let us examine more closely what we know scientifically about extinction. At the annual Congress of the American Association for the Advancement of Science, as held approximately ten years ago in Philadelphia, two papers were presented in widely-separated parts of the Congress. One was presented in anthropology and the other in biology, and though the two author-scientists knew nothing of each otherâs efforts they were closely related. The one in anthropology examined the case histories of all the known human tribes that had become extinct. The biological paper investigated the case histories of all the known biological species that had become extinct. Both scientists sought for a common cause of extinction. Both of them found a cause, and when the two papers were accidentally brought together it was discovered that the researchers had found the same causes. Extinction in both cases was the consequence of over-specialization. How does that come about?
+
+We can develop faster and faster running horses as specialists. To do so we inbreed by mating two fast-running horses. By concentrating certain genes the probability of their dominance is increased. But in doing so we breed out or sacrifice general adaptability. Inbreeding and specialization always do away with general adaptability.
+
+Thereâs a major pattern of energy in universe wherein the very large events, earthquakes, and so forth, occur in any one area of universe very much less frequently than do the small energy events. Around the Earth insects occur more often than do earthquakes. In the patterning of total evolutionary events, there comes a time, once in a while, amongst the myriad of low energy events, when a large energy event transpires and is so disturbing that with their general adaptability lost, the ultra-specialized creatures perish. I will give you a typical history-that of a type of bird which lived on a special variety of micro-marine life. Flying around, these birds gradually discovered that there were certain places in which that particular marine life tended to pocket-in the marshes along certain ocean shores of certain lands. So, instead of flying aimlessly for chance finding of that marine life they went to where it was concentrated in bayside marshes. After a while, the water began to recede in the marshes, because the Earthâs polar ice cap was beginning to increase. Only the birds with very long beaks could reach deeply enough in the marsh holes to get at the marine life. The unfed, short-billed birds died off. This left only the long-beakers. When the birdsâ inborn drive to reproduce occurred there were only other long-beakers surviving with whom to breed. This concentrated their long-beak genes. So, with continually receding waters and generation to generation inbreeding, longer and longer beaked birds were produced. The waters kept receding, and the beaks of successive generations of the birds grew bigger and bigger. The long-beakers seemed to be prospering when all at once there was a great fire in the marshes. It was discovered that because their beaks had become so heavy these birds could no longer fly. They could not escape the flames by flying out of the marsh. Waddling on their legs they were too slow to escape, and so they perished. This is typical of the way in which extinction occursâthrough over-specialization.
+
+When, as we have seen, the Great Pirates let their scientists have free rein in World War I the Pirates themselves became so preoccupied with enormous wealth harvesting that they not only lost track of what the scientists were doing within the vast invisible world but they inadvertently abandoned their own comprehensivity and they, too, became severe specialists as industrial production money makers, and thus they compounded their own acceleration to extinction in the world-paralyzing economic crash of 1929. But society, as we have seen, never knew that the Great Pirates had been running the world. Nor did society realize in 1929 that the Great Pirates had become extinct. However, worldâ society was fully and painfully aware of the economic paralysis. Society consisted then, as now, almost entirely of specialized slaves in education, management, science, office routines, craft, farming, pick-and-shovel labour, and their families. Our world society now has none of the comprehensive and realistic world knowledge that the Great Pirates had.
+
+Because world societies thought mistakenly of their local politicians, who were only the stooges of the Great Pirates, as being realistically the head men, society went to them to get the industrial and economic machinery going again. Because industry is inherently world-coordinate these world economic depression events of the 1920âS and 1930âS meant that each of the local head politicians of a number of countries were asked separately to make the world work. On this basis the world-around inventory of resources was no longer integratable. Each of the political leadersâ mandates were given from different ideological groups, and their differing viewpoints and resource difficulties led inevitably to World War II.
+
+The politicians, having an automatic bias, were committed to defend and advantage only their own side. Each assumed the validity of the Malthusian-Darwin-you-or-me-to-the-death struggle. Because of the working concept that there was not enough to go around, the most aggressive political leaders exercised their political leadership by heading their countries into war to overcome the rest of the world, thus to dispose of the unsupportable excess population through decimation and starvation-the age-old, lethal formula of ignorant men. Thus we had all our world society specializing, whether under fascism, communism, or capitalism. All the great ideological groups assumed Armageddon.
+
+Getting ready for the assumed inexorable Armageddon, each applied science and all of the great scientific specialization capabilities only toward weaponry, thus developing the ability to destroy themselves totally with no comprehensively organized oppositional thinking capability and initiative powerful enough to co-ordinate and prevent it. Thus by 1946, we were on the swift way to extinction despite the inauguration of the United Nations, to which none of the exclusive sovereign prerogatives were surrendered. Suddenly, all unrecognized as such by society, the evolutionary antibody to the extinction of humanity through specialization appeared in the form of the computer and its comprehensively commanded automation which made man obsolete as a physical production and control specialist-and just in time.
+
+The computer as superspecialist can persevere, day and night, day after day, in picking out the pink from the blue at superhumanly sustainable speeds. The computer can also operate in degrees of cold or heat at which man would perish. Man is going to be displaced altogether as a specialist by the computer. Man himself is being forced to reestablish, employ, and enjoy his innate "comprehensivlty." Coping with the totality of Spaceship Earth and universe is ahead for all of us. Evolution is apparently intent that man fulfill a much greater destiny than that of being a simple muscle and reflex machine-a slave automaton-automation displaces the automatons.
+
+Evolution consists of many great revolutionary events taking place quite independently of manâs consciously attempting to bring them about. Man is very vain; he likes to feel that he is responsible for all the favorable things that happen, and he is innocent of all the unfavorable happenings. But all the larger evolutionary patternings seeming favorable or unfavorable to manâs conditioned reflexing are transpiring transcendentally to any of manâs conscious planning or contriving.
+
+To disclose to you your own vanity of reflexing, I remind you quickly that none of you is consciously routing the fish and potato you ate for lunch into this and that specific gland to make hair, skin, or anything like that. None of you are aware of how you came to grow from 7 pounds to 70 pounds and then to I70 pounds, and so forth. All of this is automated, and always has been. There is a great deal that is automated regarding our total salvation on Earth, and I would like to get in that frame of mind right now in order to be useful in the short time we have.
+
+Let us now exercise our intellectual faculties as best we can to apprehend the evolutionary patternings transcending our spontaneous cognitions and recognitions. We may first note an evolutionary trend that countered all of the educational systems and the deliberately increased professional specialization of scientists. This contradiction occurred at the beginning of World War II, when extraordinary new scientific instruments had been developed and the biologists and chemists and physicists were meeting in Washington, D. C., on special war missions. Those scientists began to realize that whereas a biologist used to think he was dealing only in cells and that a chemist was dealing only in molecules and the physicist was dealing only in atoms, they now found their new powerful instrumentation and contiguous operations overlapping. Each specialist suddenly realized that he was concerned alike with atoms, molecules, and cells. They found there was no real dividing line between their professional interests. They hadnât meant to do this, but their professional fields were being integratedâinadvertently, on their part, but apparently purposefullyâby inexorable evolution. So, as of World War II, the scientists began to invert new professional designations: the bio-chemist, the bio-physicist, and so forth. They were forced to. Despite their deliberate attempts only to specialize, they were being merged into ever more inclusive fields of consideration. Thus was deliberately specializing man led back unwittingly once more to reemploy his innately comprehensive capabilities.
+
+I find it very important in disembarrassing ourselves of our vanity, short-sightedness, biases, and ignorance in general, in respect to universal evolution, to think in the following manner. Iâve often heard people say, âI wonder what it would be like to be on board a spaceship," and the answer is very simple. What does it feel like? Thatâs all we have ever experienced. We are all astronauts.
+
+I know you are paying attention, but Iâm sure you donât immediately agree and say, "Yes, thatâs right, I am an astronaut." Iâm sure that you donât really sense yourself to be aboard a fantastically real spaceshipâour spherical Spaceship Earth. Of our little sphere you have seen only small portions. However, you have viewed more than did pre-twentieth-century man, for in his entire lifetime he saw only one-millionth of the Earthâs surface. Youâve seen a lot more. If you are a veteran world airlines pilot you may have seen one one-hundredth of Earthâs surface. But even that is sum totally not enough to see and feel Earth to be a sphereâunless, unbeknownst to me, one of you happens to be a Cape Kennedy capsuler.
+
+4. spaceship earth
+
+Our little Spaceship Earth is only eight thousand miles in diameter, which is almost a negligible dimension in the great vastness of space. Our nearest starâour energy-supplying mother-ship, the Sunâis ninety-two million miles away, and the nearest star is one hundred thousand times further away. It takes approximately four and one third years for light to get to us from the next nearest energy supply ship star. That is the kind of space-distanced pattern we are flying. Our little Spaceship Earth is right now travelling at sixty thousand miles an hour around the around the sun and is also spinning axially, which, at the latitude of Washington, D. C., adds approximately one thousand miles per hour to our motion. Each minute we both spin at one hundred miles and zip in orbit at one thousand miles. That is a whole lot of spin and zip. When we launch our rocketed space capsules at fifteen thousand miles an hour, that additional acceleration speed we give the rocket to attain its own orbit around our speeding Spaceship Earth is only one-fourth greater than the speed of our big planetary spaceship.
+
+Spaceship Earth was so extraordinarily well invented and designed that to our knowledge humans have been on board it for two million years not even knowing that they were on board a ship. And our spaceship is so superbly designed as to be able to keep life regenerating on board despite the phenomenon, entropy, by which all local physical systems lose energy. So we have to obtain our biological life-regenerating energy from another spaceship the sun.
+
+Our sun is flying in company with us, within the vast reaches of the Galactic system, at just the right distance to give us enough radiation to keep us alive, yet not close enough to burn us up. And the whole scheme of Spaceship Earth and its live passengers is so superbly designed that the Van Allen belts, which we didnât even know we had until yesterday, filter the sun and other star radiation which as it impinges upon our spherical ramparts is so concentrated that if we went nakedly outside the Van Allen belts it would kill us. Our Spaceship Earthâs designed infusion of that radiant energy of the stars is processed in such a way that you and I can carry on safely. You and I can go out and take a sunbath, but are unable to take in enough energy through our skins to keep alive. So part of the invention of the Spaceship Earth and its biological life-sustaining is that the vegetation on the land and the algae in the sea, employing photosynthesis, are designed to impound the life-regenerating energy for us to adequate amount.
+
+But we canât eat all the vegetation. As a matter of fact, we can eat very little of it. We canât eat the bark nor wood of the trees nor the grasses. But insects can eat these, and there are many other animals and creatures that can. We get the energy relayed to us by taking the milk and meat from the animals. The animals can eat the vegetation, and there are a few of the fruits and tender vegetation petals and seeds that we can eat. We have learned to cultivate more of those botanical edibles by genetical inbreeding.
+
+That we are endowed with such intuitive and intellectual capabilities as that of discovering the genes and the R.N.A. and D.N.A. and other fundamental principles governing the fundamental design controls of life systems as well as of nuclear energy and chemical structuring is part of the extraordinary design of the Spaceship Earth, its equipment, passengers, and internal support systems. It is therefore paradoxical but strategically explicable, as we shall see, that up to now we have been mis-using, abusing, and polluting this extraordinary chemical energy-interchanging system for successfully regenerating all life aboard our planetary spaceship.
+
+One of the interesting things to me about our spaceship is that it is a mechanical vehicle, just as is an automobile. If you own an automobile, you realize that you must put oil and gas into it, and you must put water in the radiator and take care of the car as a whole. You begin to develop quite a little thermodynamic sense. You know that youâre either going to have to keep the machine in good order or itâs going to be in trouble and fail to function. We have not been seeing our Spaceship Earth as an integrally-designed machine which to be persistently successful must be comprehended and serviced in total.
+
+Now there is one outstandingly important fact regarding Spaceship Earth, and that is that no instruction book came with it. I think itâs very significant that there is no instruction book for successfully operating our ship. In view of the infinite attention to all other details displayed by our ship, it must be taken as deliberate and purposeful that an instruction book was omitted. Lack of instruction has forced us to find that there are two kinds of berries-red berries that will kill us and red berries that will nourish us. And we had to find out ways of telling which-was-which red berry before we ate it or otherwise we would die. So we were forced, because of a lack of an instruction book, to use our intellect, which is our supreme faculty, to devise scientific experimental procedures and to interpret effectively the significance of the experimental findings. Thus, because the instruction manual was missing we are learning how we safely can anticipate the consequences of an increasing number of alternative ways of extending our satisfactory survival and growth-both physical and metaphysical.
+
+Quite clearly, all of life as designed and born is utterly helpless at the moment of birth. The human child stays helpless longer than does the young of any other species. Apparently it is part of the invention "man" that he is meant to be utterly helpless through certain anthropological phases and that, when he begins to be able to get on a little better, he is meant to discover some of the physical leverage-multiplying principles inherent in universe as well as the many nonobvious resources around him which will further compoundingly multiply his knowledge-regenerating and life-fostering advantages.
+
+I would say that designed into this Spaceship Earthâs total wealth was a big safety factor which allowed man to be very ignorant for a long time until he had amassed enough experiences from which to extract progressively the system of generalized principles governing the increases of energy managing advantages over environment. The designed omission of the instruction book on how to operate and maintain Spaceship Earth and its complex life-supporting and regenerating systems has forced man to discover retrospectively just what his most important forward capabilities are. His intellect had to discover itself. Intellect in turn had to compound the facts of his experience. Comprehensive reviews of the compounded facts of experiences by intellect brought forth awareness of the generalized principles underlying all special and only superficially-sensed experiences. Objective employment of those generalized principles in rearranging the physical resources of environment seems to be leading to humanityâs eventually total success and readiness to cope with far vaster problems of universe.
+
+To comprehend this total scheme we note that long ago a man went through the woods, as you may have done, and I certainly have, trying to find the shortest way through the woods in a given direction. He found trees fallen across his path. He climbed over those crisscrossed trees and suddenly found himself poised on a tree that was slowly teetering. It happened to be lying across another great tree, and the other end of the tree on which he found himself teetering lay under a third great fallen tree. As he teetered he saw the third big tree lifting. It seemed impossible to him. He went over and tried using his own muscles to lift that great tree. He couldnât budge it. Then he climbed back atop the first smaller tree, purposefully teetering it, and surely enough it again elevated the larger tree. Iâm certain that the first man who found such a tree thought that it was a magic tree, and may have dragged it home and erected it as manâs first totem. It was probably a long time before he learned that any stout tree would do, and thus extracted the concept of the generalized principle of leverage out of all his earlier successive special-case experiences with such accidental discoveries. Only as he learned to generalize fundamental principles of physical universe did man learn to use his intellect effectively.
+
+Once man comprehended that any tree would serve as a lever his intellectual advantages accelerated. Man freed of special-case superstition by intellect has had his survival potentials multiplied millions fold. By virtue of the leverage principles in gears, pulleys, transistors, and so forth, it is literally possible to do more with less in a multitude of physio-chemical ways. Possibly it was this intellectual augmentation of humanityâs survival and success through the metaphysical perception of generalized principles which may be objectively employed that Christ was trying to teach in the obscurely told story of the loaves and the fishes.
+
+5. general systems theory
+
+How may we use our intellectual capability to higher advantage? Our muscle is very meager as compared to the muscles of many animals. Our integral muscles are as nothing compared to the power of a tornado or the atom bomb which society contrived-in fear-out of the intellectâs fearless discoveries of generalized principles governing the fundamental energy behaviors of physical universe.
+
+In organizing our grand strategy we must first discover where we are now; that is, what our present navigational position in the universal scheme of evolution is. To begin our position-fixing aboard our Spaceship Earth we must first acknowledge that the abundance of immediately consumable, obviously desirable or utterly essential resources have been sufficient until now to allow us to carry on despite our ignorance. Being eventually exhaustible and spoilable, they have been adequate only up to this critical moment. This cushion-for-error of humanityâs survival and growth up to now was apparently provided just as a bird inside of the egg is provided with liquid nutriment to develop it to a certain point. But then by design the nutriment is exhausted at just the time when the chick is large enough to be able to locomote on its own legs. And so as the chick pecks at the shell seeking more nutriment it inadvertently breaks open the shell. Stepping forth from its initial sanctuary, the young bird must now forage on its own legs and wings to discover the next phase of its regenerative sustenance.
+
+My own picture of humanity today finds us just about to step out from amongst the pieces of our just one-second-ago broken eggshell. Our innocent, trial-and-error-sustaining nutriment is exhausted. We are faced with an entirely new relationship to the universe. We are going to have to spread our wings of intellect and fly or perish; that is, we must dare immediately to fly by the generalized principles governing universe and not by the ground rules of yesterdayâs superstitious and erroneously conditioned reflexes. And as we attempt competent thinking we immediately begin to reemploy our innate drive for comprehensive understanding.
+
+The architects and planners, particularly the planners, though rated as specialists, have a little wider focus than do the other professions. Also as human beings they often battle the narrow views of specialistsâin particular, their patronsâthe politicians, and the financial and other legal, but no longer comprehensively effective, heirs to the great piratesâânow only ghostlyâprerogatives. At least the planners are allowed to look at all of Philadelphia, and not just to peek through a hole at one house or through one door at one room in that house. So I think itâs appropriate that we assume the role of planners and begin to do the largest scale comprehensive thinking of which we are capable.
+
+We begin by eschewing the role of specialists who deal only in parts. Becoming deliberately expansive instead of contractive, we ask, "How do we think in terms of wholes?" If it is true that the bigger the thinking becomes the more lastingly effective it is, we must ask, "How big can we think?"
+
+One of the modern tools of high intellectual advantage is the development of what is called general systems theory. Employing it we begin to think of the largest and most comprehensive systems, and try to do so scientifically. We start by inventorying all the important, known variables that are operative in the problem. But if we donât really know how big "big" is, we may not start big enough, and are thus likely to leave unknown, but critical, variables outside the system which will continue to plague us. Interaction of the unknown variables inside and outside the arbitrarily chosen limits of the system are probably going to generate misleading or outrightly wrong answers. If we are to be effective, we are going to have to think in both the biggest and most minutely-incisive ways permitted by intellect and by the information thus far won through experience.
+
+Can we think of, and state adequately and incisively, what we mean by universe? For universe is, inferentially, the biggest system. If we could start with universe, we would automatically avoid leaving out any strategically critical variables. We find no record as yet of man having successfully defined the universe-scientifically and comprehensively-to include the nonsimultaneous and only partially overlapping, micro-macro, always and everywhere transforming, physical and metaphysical, omni-complementary but nonidentical events.
+
+Man has failed thus far, as a specialist, to define the microcosmic limits of divisibility of the nucleus of the atom, but, epochally, as accomplished by Einstein, has been able to define successfully the physical universe but not the metaphysical universe; nor has he, as yet, defined total universe itself as combining both the physical and metaphysical. The scientist was able to define physical universe by virtue of the experimentally-verified discovery that energy can neither be created nor lost and, therefore, that energy is conserved and is therefore finite. That means it is equatable.
+
+Einstein successfully equated the physical universe as E = Mc2. His definition was only a hypothetical venture until fission proved it to be true. The physical universe of associative and disassociative energy was found to be a closed, but nonsimultaneously occurring, system-its separately occurring events being mathematically measurable; i.e., weighable and equatable. But the finite physical universe did not include the metaphysical weightless experiences of universe. All the unweighables, such as any and all our thoughts and all the abstract mathematics, are weightless. The metaphysical aspects of universe have been thought by the physical scientists to defy "closed systemâs" analysis. I have found, however, as we shall soon witness, that total universe including both its physical and metaphysical behaviors and aspects are scientifically definable.
+
+Einstein and others have spoken exclusively about the physical department of universe in words which may be integrated and digested as the aggregate of nonsimultaneous and only partially overlapping, nonidentical, but always complementary, omni-transforming, and weighable energy events. Eddington defines science as "the earnest attempt to set in order the facts of experience." Einstein and many other first-rank scientists noted that science is concerned exclusively with "facts of experience."
+
+Holding to the scientistsâ experiences as all important, I define universe, including both the physical and metaphysical, as follows: The universe is the aggregate of all of humanityâs consciously-apprehended and communicated experience with the nonsimultaneous, nonidentical, and only partially overlapping, always complementary, weighable and unweighable, ever omni-transforming, event sequences.
+
+Each experience begins and ends-ergo, is finite. Because our apprehending is packaged, both physically and metaphysically, into time increments of alternate awakeness and asleepness as well as into separate finite conceptions such as the discrete energy quanta and the atomic nucleus components of the fundamental physical discontinuity, all experiences are finite. Physical experiments have found no solids, no continuous surfaces or linesâonly discontinuous constellations of individual events. An aggregate of finites is finite. Therefore, universe as experientially defined, including both the physical and metaphysical, is finite.
+
+It is therefore possible to initiate our general systems formulation at the all inclusive level of universe whereby no strategic variables will be omitted. There is an operational grand strategy of General Systems Analysis that proceeds from here. It is played somewhat like the game of "Twenty Questions," but G. S. A. is more efficientâthat is, is more economicalâin reaching its answers. It is the same procedural strategy that is used by the computer to weed out al1 the wrong answers until only the right answer is left.
+
+Having adequately defined the whole system we may proceed to subdivide progressively. This is accomplished through progressive division into two partsâone of which, by definition, could not contain the answerâand discarding of the sterile part. Each progressively-retained live part is called a "bit" because of its being produced by the progressive binary "yes" or "no" bi-section of the previously residual live part. The magnitude of such weeding operations is determined by the number of successive bits necessary to isolate the answer.
+
+How many "bi-secting bits" does it take to get rid of all the irrelevancies and leave in lucid isolation that specific information you are seeking? We find that the first subdividing of the concept of universe-bit oneâis into what we call a system. A system subdivides universe into all the universe outside the system (macrocosm) and all the rest of the universe which is inside the system (microcosm) with the exception of the minor fraction of universe which constitutes the system itself. The system divides universe not only into macrocosm and microcosm but also coincidentally into typical conceptual and nonconceptual aspects of universe-that is, an overlappingly-associable consideration, on the one hand, and, on the other hand, all the nonassociable, nonoverlappingly-considerable, nonsimultaneously-transforming events of nonsynchronizable disparate wave frequency rate ranges.
+
+A thought is a system, and is inherently conceptual-though often only dimly and confusedly conceptual at the moment of first awareness of the as yet only vaguely describable thinking activity. Because total universe is nonsimultaneous it is not conceptual. Conceptuality is produced by isolation, such as in the instance of one single, static picture held out from a moving-picture filmâs continuity, or scenario. Universe is an evolutionary-process scenario without beginning or end, because the shown part is continually transformed chemically into fresh film and reexposed to the ever self-reorganizing process of latest thought realizations which must continually introduce new significance into the freshly written description of the ever-transforming events before splicing the film in again for its next projection phase.
+
+Heisenbergâs principle of "indeterminism" which recognized the experimental discovery that the act of measuring always alters that which was being measured turns experience into a continuous and never-repeatable evolutionary scenario. One picture of the scenario about the caterpillar phase does not communicate its transformation into the butterfly phase, etc. The question, "I wonder what is outside the outside-of-universe?" is a request for a single picture description of a scenario of transformations and is an inherently invalid question. It is the same as looking at a dictionary and saying, â"Which word is the dictionary?" It is a meaningless question.
+
+It is characteristic of "all" thinkingâof all systemâs conceptioningâthat all the lines of thought interrelationships must return cyclically upon themselves in a plurality of directions, as do various great circles around spheres. Thus may we interrelatedly comprehend the constellation-or system-of experiences under consideration. Thus may we comprehend how the special-case economy demonstrated by the particular system considered also discloses the generalized law of energy conservation of physical universe.
+
+To hit a duck in flight a hunter does not fire his gun at the bird where the gunner sees him but ahead of the bird, so that the bird and the bullet will meet each other at a point not in line between the gunner and the bird at time of firing. Gravity and wind also pull the bullet in two different directions which altogether impart a mild corkscrew trajectory to the bullet. Two airplanes in nighttime dogfights of World War II firing at each other with tracer bullets and photographed by a third plane show clearly the corkscrew trajectories as one hits the other. Einstein and Reiman, the Hindu mathematician, gave the name geodesic lines to these curvilinear and most economical lines of interrelationship between two independently moving "events"âthe events in this case being the two airplanes.
+
+A great circle is a line formed on a sphereâs surface by a plane going through the sphereâs centre. Lesser circles are formed on the surfaces of spheres by planes cutting through spheres but not passing through the sphereâs centre. When a lesser circle is superimposed on a great circle it cuts across the latter at two points, A and B. It is a shorter distance between A and B on the great circleâs shortest arc than it is on the lesser circleâs shortest arc. Great circles are geodesic lines because they provide the most economical (energy, effort) distances between any two points on a spherical systemâs surface; therefore, nature, which always employs only the most economical realizations, must use those great circles which, unlike spiral lines, always return upon themselves in the most economical manner. All the systemâs paths must be topologically and circularly interrelated for conceptually definitive, locally transformable, polyhedronal understanding to be attained in our spontaneous-ergo, most economical- geodesicly structured thoughts.
+
+Thinking itself consists of self-disciplined dismissal of both the macrocosmic and microcosmic irrelevancies which leaves only the lucidly-relevant considerations. The macrocosmic irrelevancies are all the events too large and too infrequent to be synchronizably tuneable in any possible way with our consideration (a beautiful word meaning putting stars together). The microcosmic irrelevancies are all the events which are obviously too small and too frequent to be differentially resolved in any way or to be synchronizably-tuneable within the lucidly-relevant wave-frequency limits of the system we are considering.
+
+How many stages of dismissal of irrelevancies does it take-that is, proceeding from "universe" as I defined it, how many bits does it take-lucidly to isolate all the geodesic interrelations of all the "star" identities in the constellation under consideration? The answer is the formula (redo in finished text) where N is the number of stars in the thought-discerned constellation of focal point entities comprising the problem.
+
+"Comprehension" means identifying all the most uniquely economical inter-relationships of the focal point entities involved. We may say then that:
+
+Comprehension = (redo in finished text)
+
+This is the way in which thought processes operate with mathematical logic. The mathematics involved consist of topology, combined with vectorial geometry, which combination I call "synergetics"-which word I will define while clarifying its use. By questioning many audiences, I have discovered that only about one in three hundred are familiar with synergy. The word is obviously not a popular word. Synergy is the only word in our language that means behavior of whole systems unpredicted by the separately observed behaviors of any of the systemâs separate parts or any subassembly of the systemâs parts. There is nothing in the chemistry of a toenail that predicts the existence of a human being.
+
+I once asked an audience of the National Honors Society in chemistry, "How many of you are familiar with the word, synergy?" and all hands went up. Synergy is the essence of chemistry. The tensile strength of chrome-nickel-steel, which is approximately 350,000 pounds per square inch, is 100,OOO P.S.I. greater than the sum of the tensile strengths of each of all its alloyed together, component, metallic elements. Here is a "chain" that is 50 per cent stronger than the sum of the strengths of all its links. We think popularly only in the terms of a chain being no stronger than its weakest link, which concept fails to consider, for instance, the case of an endlessly interlinked chain of atomically self-renewing links of omni-equal strength or of an omni-directionally interlinked chain matrix of ever renewed atomic links in which one broken link would be, only momentarily, a local cavern within the whole mass having no weakening effect on the whole, for every link within the matrix is a high frequency, recurring, break-and-make restructuring of the system.
+
+Since synergy is the only word in our language meaning behavior of wholes unpredicted by behavior of their parts, it is clear that society does not think there are behaviors of whole systems unpredicted by their separate parts. This means that societyâs formally-accredited thoughts and ways of accrediting others are grossly inadequate in comprehending the nonconceptual qualities of the scenario "universal evolution."
+
+There is nothing about an electron alone that forecasts the proton, nor is there anything about the Earth or the Moon that forecasts the co-existence of the Sun. The solar system is synergetic-unpredicted by its separate parts. But the interplay of Sun as supply ship of Earth and the Moonâs gravitationally produced tidal pulsations on Earth all interact to produce the biosphereâs chemical conditions which permit but do not cause the regeneration of life on Spaceship Earth. This is all synergetic. There is nothing about the gases given off respiratorily by Earthâs green vegetation that predicts that those gases will be essential to the life support of all mammals aboard Spaceship Earth, and nothing about the mammals that predicts that the gases which they give off respiratorily are essential to the support of the vegetation aboard our Spaceship Earth. Universe is synergetic. Life is synergetic.
+
+Summarizing synergetically I may conclude that since my experimental interrogation of more than one hundred audiences all around the world has shown that less than one in three hundred university students has ever heard of the word synergy, and since it is the only word that has that meaning it is obvious that the world has not thought there are any behaviors of whole systems unpredictable by their parts. This is partially the consequence of over-specialization and of leaving the business of the whole to the old pirates to be visibly conducted by their stooges, the feudal kings or local politicians.
+
+There is a corollary of synergy which says that the known behavior of the whole and the known behavior of a minimum of known parts often makes possible the discovery of the values of the remaining parts as does the known sum of the angles of a triangle plus the known behavior of three of its six parts make possible evaluating the others. Topology provides the synergetic means of ascertaining the values of any system of experiences.
+
+Topology is the science of fundamental pattern and structural relationships of event constellations. It was discovered and developed by the mathematician Euler. He discovered that all patterns can be reduced to three prime conceptual characteristics: to lines; points where two lines cross or the same line crosses itself; and areas, bound by lines. He found that there is a constant relative abundance of these three fundamentally unique and no further reducible aspects of all patterning
+
+P + A = L + 2
+
+This reads: the number of points plus the number of areas always equals the number of lines plus the number constant two. There are times when one area happens to coincide with others. When the faces of polyhedra coincide illusionarily the congruently hidden faces must be accounted arithmetically in formula.
+
+6. synergy
+
+We will now tackle our present world problems with the family of powerful thought tools: topology, geodesics, synergetics, general systems theory, and the computerâs operational "bitting." To insure our inclusion of all the variables with which we must eventually deal, we will always start synergetically with universe -now that universe is defined and thus provides us with the master containment. We will then state our unique problem and divest ourselves progressively and definitively of all the micromacro irrelevancies. Are humans necessary? Are there experiential clues that human intellect has an integral function in regenerative universe as has gravity? How can Earthians fulfill their function and thus avoid extinction as unfit?
+
+To start with, we will now progressively subdivide universe and isolate the thinkable concept by bits through progressively dismissing residual irrelevancies. Our first isolated bit is the system, which at maximum is the starry macrocosmic and at minimum the atomic nucleus; the second bit reduces the macrocosmic limit to that of the galactic nebula; the third bit separates out cosmic radiation, gravity and the solar system; and the fourth bit isolates the cosmic radiation, gravity, sun, its energized, life-bearing Spaceship Earth, together WITH the Earthâs Moon as the most prominent components of the life regeneration on Spaceship Earth.
+
+I would like to inventory rapidly the system variables which I find to be by far the most powerful in the consideration of our present life-regenerating evolution aboard our spaceship as it is continually refueled radiationally by the Sun and other cosmic radiation. Thus we may, by due process, suddenly and excitingly discover why we are here alive in universe and identify ourselves as presently operating here, aboard our spaceship, and situated aboard its spherical deck at, for example, Washington, D. C., on the North American continent, thinking effectively regarding the relevant contemporary and local experiences germane to the solution of humanityâs successful and happy survival aboard our planet. We may thus discover not only what needs to be done in a fundamental way but also we may discover how it may be accomplished by our own directly-seized initiative, undertaken and sustained without any further authority than that of our function in universe, where the most ideal is the most realistically practical. Thus we may avoid all the heretofore frustrating factors of uninspired patron guidance of our work such as the patronâs supine concessions to the nonsynergetical thinking, and therefore ignorantly conditioned reflexes, of the least well advised of the potential mass customers.
+
+Typical of the subsidiary problems within the whole human survival problem, whose ramifications now go beyond the prerogatives of planners and must be solved, is the problem of pollution in general-pollution not only of our air and water but also of the information stored in our brains. We will soon have to rename our planet "Poluto." In respect to our planetâs life sustaining atmosphere we find that, yes, we do have technically feasible ways of precipitating the fumes, and after this we say, "But it costs too much." There are also ways of desalinating sea water, and we say, "But it costs too much." This too narrow treatment of the problem never faces the inexorably-evolving and solution-insistent problem of what it will cost when we donât have the air and water with which to survive. It takes months to starve to death, weeks to thirst to death, but only minutes to suffocate. We cannot survive without water for the length of time it takes to produce and install desalinization equipment adequate to supply, for instance, all of New York City. A sustained, and often threatened, water shortage in New York City could mean death for millions of humans. Each time the threat passes the old statement "it costs too much" again blocks realization of the desalinization capability.
+
+Anybody who has been in Washington (and approximately everyone else everywhere today) is familiar with governmental budgeting and with the modes of developing public recognition of problems and of bringing about official determination to do something about solutions. In the end, the problems are rarely solved, not because we donât know how but because it is discovered either that it is said by those in authority that "it costs too much" or that when we identify the fundamental factors of the environmental problemsâand laws are enacted to cope incisively with those factors that there are no funds presently known to be available with which to implement the law. There comes a money bill a year later for implementation and with it the political criteria of assessing wealth by which the previous yearâs bill would now seemingly "cost too much." So compromises follow compromises. Frequently, nothing but political promises or under-budgeted solutions result. The original legislation partially stills the demands. The pressures on the politicians are lowered, and the lack of implementation is expeditiously shrugged off because of seemingly more pressing, seemingly higher priority, new demands for the money. The most pressing of those demands is for war, for which the politicians suddenly accredit weaponry acquisitions and military tasks costing many times their previously asserted concepts of what we can afford.
+
+Thus under lethal emergencies vast new magnitudes of wealth come mysteriously into effective operation. We donât seem to be able to afford to do peacefully the logical things we say we ought to be doing to forestall warring-by producing enough to satisfy all the world needs. Under pressure we always find that we can afford to wage the wars brought about by the vital struggle of "have-nots" to share or take over the bounty of the "haves." Simply because it had seemed, theretofore, to cost too much to provide vital support of those "have-nots." The "haves" are thus forced in self-defense suddenly to articulate and realize productive wealth capabilities worth many times the amounts of monetary units they had known themselves to possess and, far more importantly, many times what it would have cost to give adequate economic support to the particular "have-nots" involved in the warring and, in fact, to all the worldâs âhave-nots."
+
+The adequately macro-comprehensive and micro-incisive solutions to any and all vital problems never cost too much. The production of heretofore nonexistent production tools and industrial networks of harnessed energy to do more work does not cost anything but human time which is refunded in time gained minutes after the inanimate machinery goes to work. Nothing is spent. Potential wealth has become real wealth. As it is cliched "in the end" problem solutions always cost the least if paid for adequately at outset of the vital problemâs recognition. Being vital, the problems are evolutionary, inexorable, and ultimately unavoidable by humanity. The constantly put-off or under-met costs and societyâs official bumbling of them clearly prove that man does not know at present what wealth is nor how much of whatever it may be is progressively available to him.
+
+We have now flushed out a major variable in our general systems problem of man aboard Spaceship Earth. The question âWhat is wealth?" commands our prime consideration.
+
+The Wall Sheet Journal reported the September-October 1967 deliberations of the International Monetary Fund held at Rio De Janeiro, BraziI. Many years and millions of dollars were spent maneuvering for and assembling this monetary convention, and the net result was the weak opinion that it would soon be time to consider doing something about money. The convention felt our international balance of payments and its gold demand system to be inadequate. They decided that the old pirateâs gold was still irreplaceable but that after a few years they might have to introduce some new "gimmick" to augment the gold as an international monetary base.
+
+At present there is about seventy billion dollars of mined gold known to exist on board our Spaceship Earth. A little more than half of it-about forty billion-is classified as being "monetary"; that is, it exists in the forms of various national coinages or in the form of officially banked gold bullion bars. The remaining thirty billion is in private metallic hordes, jewelry, gold teeth, etc.
+
+Since banks have no money of their own and only our deposits on which they earn "interest," bank wealth or money consists only of accrued bank income. Income represents an average return of 5 per cent on capital invested. We may assume therefore from an estimate of the worldâs annual gross product that the capital assets, in the form of industrial production, on board our Spaceship Earth are at present worth in excess of a quadrillion dollars. The worldâs total of seventy billion dollars in gold represents only three one-thousandths of I per cent of the value of the worldâs organized industrial production resources. The gold supply is so negligible as to make it pure voodoo to attempt to valve the worldâs economic evolution traffic through the gold-sized needleâs "eye."
+
+Gold was used for trading by the Great Pirates in lieu of any good faith whatsoeverâand in lieu of any mutual literacy, scientific knowledge, intelligence, or scientific and technical know-how on both sides of the trading. Gold trading assumed universal rascality to exist. Yet the realization of the plannersâ earnest conceptioning and feasible work on behalf of the ill-fated 60 per cent of humanity are entirely frustrated by this kind of nonsense.
+
+We therefore proceed ever more earnestly with our general systems analysis of the problems of human survival, with the premise that at present neither the worldâs political officials nor its bankers know what wealth is. In organizing our thoughts to discover and clarify what wealth is we also will attempt to establish an effective means to develop immediate working procedures for solution of such big problems.
+
+I have tried out the following intellectual filtering procedure with both multi-thousand general public audiences and with audiences of only a hundred or so advanced scholars and have never experienced disagreement with my progression of residual conclusions. I proceed as follows: I am going to make a series of analytical statements to you, and if anyone disagrees with me on any statement we will discard that statement. Only those of all my statements which remain 100 per cent unprotected will we rate as being acceptable to all of us.
+
+First, I say, "No matter what you think wealth may be and no matter how much you have of it, you cannot alter one iota of yesterday." No protest? Weâve learned some lessons. We can say that wealth is irreversible in evolutionary processes. Is there anyone who disagrees with any of my statements thus farâabout what wealth is or is not? Good-no disagreement-we will go on.
+
+Now, Iâm going to have a man in a shipwreck. Heâs rated as a very rich man, worth over a billion dollars by all of societyâs accredited conceptions of real wealth. He has taken with him on his voyage all his stocks and bonds, all his property deeds, all his checkbooks, and, to play it safe, has brought along a lot of diamonds and gold bullion. The ship burns and sinks, and there are no lifeboats, for they, too, have burned. If our billionaire holds on to his gold, heâs going to sink a little faster than the others. So I would say he hadnât much left either of now or tomorrow in which to articulate his wealth, and since wealth cannot work backwardly his kind of wealth is vitally powerless. It is really a worthless pile of chips of an arbitrary game which we are playing and does not correspond to the accounting processes of our real universeâs evolutionary transactions. Obviously the catastrophied billionaireâs kind of wealth has no control over either yesterday, now, or tomorrow. He canât extend his life with that kind of wealth unless he can persuade the one passenger who has a life-jacket to yield that only means of extending one life in exchange for one crazy momentâs sense of possession of all the billionaireâs sovereign-powers-backed legal tender, all of which the catastrophy-disillusioned and only moments earlier "powerfully rich" and now desperately helpless man would thankfully trade for the physical means of extending the years of his life; or of his wife.
+
+It is also worth remembering that the validity of what our reputedly rich man in the shipwreck had in those real estate equities went back only to the validity "in the eyes of God" of the original muscle, cunning, and weapons-established-sovereign-claimed lands and their subsequent legal re-deedings as "legal" properties protected by the moral-or-no, weapons-enforced laws of the sovereign nations and their subsequent abstraction into limited-liability-corporation equities printed on paper stocks and bonds. The procedure we are pursuing is that of true democracy. Semi-democracy accepts the dictatorship of a majority in establishing its arbitrary, ergo, unnatural, laws. True democracy discovers by patient experiment and unanimous acknowledgement what the laws of nature or universe may be for the physical support and metaphysical satisfaction of the human intellectâs function in universe.
+
+I now go on to speculate that I think that what we all really mean by wealth is as follows: "Wealth is our organized capability to cope effectively with the environment in sustaining our healthy regeneration and decreasing both the physical and metaphysical restrictions of the forward days of our lives."
+
+Is there any disagreement? Well, having first disposed of what wealth is not we now have produced a culled-out statement that roughly contains somewhere within it a precise definition of what wealth is. Now we can account wealth more precisely as the number of forward days for a specific number of people we are physically prepared to sustain at a physically stated time and space liberating level of metabolic and metaphysical regeneration.
+
+We are getting sharper. Inasmuch as we now are learning more intimately about our Spaceship Earth and its radiation supply ship Sun on the one hand and on the other its Moon acting as the Earthâs gravitationally pulsing "alternator" which together constitute the prime generator and regenerator of our life supporting system, I must observe also that weâre not going to sustain life at all except by our successful impoundment of more of the Sunâs radiant energy aboard our spaceship than we are losing from Earth in the energies of radiation or outwardly rocketed physical matter. We could burn up the Spaceship Earth itself to provide energy, but that would give us very little future. Our space vehicle is similar to a human child. It is an increasing aggregate of physical and metaphysical processes in contradistinction to a withering, decomposing corpse.
+
+It is obvious that the real wealth of life aboard our planet is a forwardly-operative, metabolic, and intellectual regenerating system. Quite clearly we have vast amounts of income wealth as Sun radiation and Moon gravity to implement our forward success. Wherefore living only on our energy savings by burning up the fossil fuels which took billions of years to impound from the Sun or living on our capital by burning up our Earthâs atoms is lethally ignorant and also utterly irresponsible to our coming generations and their forward days. Our children and their children are our future days. If we do not comprehend and realize our potential ability to support all life forever we are cosmicly bankrupt.
+
+Having identified the ignorance of society regarding its wealth capabilities to be a major factor in the frustration of effective planning and having roughly identified the meaning of wealth to which everyone can realistically subscribe, and intending later to sharpen its identity, we will now tackle the next phase of humanityâs total survival, prosperity, happiness, and regenerative inspiration with the problem-solving power of General Systems Theory as combined with both computer strategy-which is known as cybernetics-and with synergetics -the latter consisting of the solving of problems by starting with known behaviors of whole systems plus the known behaviors of some of the systemsâ parts, which advantageous information makes possible the discovery of other parts of the system and their respective behaviors, as for instance in geometry the known sum-180 degrees-of a triangleâs angles, plus the known behavior of any two sides and their included angle and vice versa, enables the discovery and use of the precise values of the other three parts.
+
+Synergetics discloses that wealth, which represents our ability to deal successfully with our forward energetic regeneration and provide increased degrees of freedom of initiation and noninterfering actions, breaks down cybernetically into two main parts: physical energy and metaphysical know-how. Physical energy in turn divides into two interchangeable phases: associative and disassociativeâenergy associative as matter and energy disassociative as radiation.
+
+Stating first that physical universe is all energy and symbolizing energy by E, Einstein formulated his famous equation E = M (matterâs mass, explained in the terms of C2âspeed of an omni-directional [radiant] surface waveâs expansion, unfettered, in a vacuum). Energy as matter and energy as radiation, as Einstein had generalized hypothetically, were explicitly proven by fission to be interchangeable covariants.
+
+Physicists also have discovered experimentally that energy can neither be exhausted nor originated. Energy is finite and infinitely conserved. This experimentally proven realization of some prime facts of physical universe contradicts the thoughts of cosmologists, cosmogonists, and societyâs economics expressed before the speed of light was measured at the beginning of the twentieth century.
+
+I came to Harvard University in the beginning of the century-just before World War I. At that time, it was as yet the consensus of scholarly thinking that because the universe itself was seemingly a system it, too, must be subject to entropy, by which every (local) system was found experimentally to be continually losing energy. Hence, the universe itself was thought to be losing energy. This indicated that the universe was "running down," at which time evolution would abandon its abnormal energetic behavior and all would return to Newtonâs norm of "at rest." This being so, it was also assumed that all those who expended energy were recklessly speeding the end. This was the basis of yesterdayâs conservatism. All who expended energy in bringing about further evolutionary changes were to be abhorred. They were to be known as reckless spenders.
+
+All this was assumed to be true before experiments at the beginning of the twentieth century gave scientists knowledge of the speed of light and of radiation in general. Thus, we suddenly discovered it took eight minutes for the light to get to us from the sun, two and one-half years from the next nearest star beyond the sun, and many years for it to reach us from other stars. We learned only two-thirds of a century ago that many stars we considered as instantly there had burned out thousands of years ago. Universe is not simultaneous.
+
+Then Einstein, Planck, and other leading scientists said, "Weâre going to have to reassess and redefine the physical universe.- They defined the physical universe as "an aggregate of non-simultaneous and only partially overlapping transformation events." And they then said: "We must discover what it is we see when we observe new life forming. It could be that when energy disassociates here it always may be reassociating somewhere else." And that in all subsequent experimentation proved to be the case. The scientists found that the energy redistributions always added up to 100 per cent. The scientists then formulated a new description of the physical universe which they called the new "law of conservation of energy," which said that "physical experiments disclose that energy can neither be created nor lost.. Energy is not only conserved but it is also finite. It is a closed system. The universe is a mammoth perpetual motion process. We then see that the part of our wealth which is physical energy is conserved. It cannot be exhausted, cannot be spent, which means exhausted. We realize that the word "spending" is now scientifically meaningless and is therefore obsolete.
+
+I referred earlier to manâs discovery of the lever. Having used levers for millenniums, man thought of taking a series of bucket-ended levers and of inserting the nonbucket end of each lever perpendicularly into a shaftâarranged one after another like spokes around a wheel. He mounted that shaft in bearings, put it under a waterfall, and let gravity fill each bucket in turn and then pull each filled bucket toward the center of the planet Earth, thus progressively rotating all the levers and making the wheel and its shaft rotate with great power. Then man connected this revolving shaft by pulley belts to other pulleys on other shafts which drove machines to do many metabolically-regenerating tasks in a way unmatchable by manâs muscle power alone. Man thus began for the first time to really employ his intellect in the most important way. He discovered how to use energy as matter in the form of levers, shafts, gear trains, and dams, and how to take advantage of and use the energy as Sun radiation which vaporized and elevated water as atmospheric cloud, allowing it then to be precipitated and pulled back toward the center of the spherical Earth from the spherical mantle of clouds in the form of water molecules collected in droplets. From this moment of comprehending energy circuits, and thenceforth, manâs really important function in universe was his intellection, which taught him to intercept and redirect local energy patternings in universe and thus to reorganize and shunt those flow patterns so that they would impinge on levers to increase humanityâs capabilities to do the manifold tasks leading directly and indirectly toward humanityâs forward metabolic regeneration.
+
+What we now have demonstrated metaphysically is that every time man makes a new experiment he always learns more. He cannot learn less. He may learn that what he thought was true was not true. By the elimination of a false premise, his basic capital wealth which in his given lifetime is disembarrassed of further preoccupation with considerations of how to employ a worthless time-consuming hypothesis. Freeing his time for its more effective exploratory investment is to give man increased wealth.
+
+We find experimentally, regarding the metaphysical phenomenon, intellect, which we call know-how, that every time we employ and test our intellectual know-how by experimental
+rearrangement of physical energy interactions (either associated as mass or disassociated as radiation, free energy) we always learn more. The know-how can only increase. Very interesting. Now we have carefully examined and experimented with the two basic constituents of wealth-the physical and the metaphysical.
+
+Sum-totally, we find that the physical constituent of wealth-energy-cannot decrease and that the metaphysical constituent-know-how-can only increase. This is to say that everytime we use our wealth it increases. This is to say that, countering entropy, wealth can only increase. Whereas entropy is increasing disorder evoked by dispersion of energy, wealth locally is increased order-that is to say, the increasingly orderly concentration of physical power in our ever-expanding locally explored and comprehended universe by the metaphysical capability of man, as informed by repeated experiences from which he happens in an unscheduled manner to progressively distill the ever-increasing inventory of omni-interrelated and omni-interaccommodative generalized principles found to be operative in all the special-case experiences. Irreversible wealth is the so far attained effective magnitude of our physically organized ordering of the use of those generalized principles.
+
+Wealth is anti-entropy at a most exquisite degree of concentration. The difference between mind and brain is that brain deals only with memorized, subjective, special-case experiences and objective experiments, while mind extracts and employs the generalized principles and integrates and interrelates their effective employment. Brain deals exclusively with the physical, and mind exclusively with the metaphysical. Wealth is the product of the progressive mastery of matter by mind, and is specifically accountable in forward man-days of established metabolic regeneration advantages spelt out in hours of life for specific numbers of individuals released from formerly prescribed entropy-preoccupying tasks for their respectively individual yet inherently co-operative elective investment in further anti-entropic effectiveness.
+
+Because our wealth is continually multiplying in vast degree unbeknownst and unacknowledged formally by human society, our economic accounting systems are unrealistically identifying wealth only as matter and are entering know-how on the books only as salary liabilities; therefore, all that we are discovering mutually here regarding the true nature of wealth comes as a complete surprise to world societyâto both communism and to capitalism alike. Both social co-operation and individual enterprise interact to produce increasing wealth, all unrecognized by ignorantly assumed lethally competitive systems. All our formal accounting is anti-synergetic, depreciative, and entropic mortgagization, meaning death by inversally compounding interest. Wealth as anti-entropy developes compound interest through synergy, which growth is as yet entirely unaccounted anywhere around Earth in any of its political economic systems. We give an intrinsic value to the material. To this we add the costs of manufacturing which include energy, labor, overhead, and profit. We then start depreciating this figure assuming swift obsolescence of the value of the product. With the exception of small royalties, which are usually avoided, no value is given for the inventiveness or for the synergistic value given by one product to another by virtue of their complementarity as team components whose teamwork produces results of enormous advantage, as for instance do the invention of alloyed drill bits of oil rigs bring petroleum from nonuse to use.
+
+As a consequence of true wealthâs unaccounted, inexorably synergistic multiplication of ever-increasing numbers of humanityâs ever-increasing forward days, in this century alone we have gone from less than I per cent of humanity being able to survive in any important kind of health and comfort to 44 per cent of humanity surviving at a standard of living unexperienced or undreamed of before. This utterly unpredicted synergistic success occurred within only two-thirds of a century despite continually decreasing metallic resources per each world person. It happened without being consciously and specifically attempted by any government or business. It also happened only as a consequence of manâs inadvertently becoming equipped synergistically to do progressively more with less.
+
+As we have learned, synergy is the only word in our language which identifies the meaning for which it stands. Since the word is unknown to the average public, as I have already pointed out, it is not at all surprising that synergy has not been included in the economic accounting of our wealth transactions or in assessing our common wealth capabilities. The synergetic aspect of industryâs doing ever more work with ever less investment of time and energy per each unit of performance of each and every function of the weapons carriers of the sea, air, and outer space has never been formally accounted as a capital gain of land-situated society. The synergistic effectiveness of a world-around integrated industrial process is inherently vastly greater than the confined synergistic effect of sovereignly operating separate systems. Ergo, only complete world desovereignization can permit the realization of an all humanity high standard support. But the scientific facts are that simple tools that make complex tools are synergetically augmented by progressively more effective and previously unpredicted chemical elements alloying. The whole history of world industrialization demonstrates constantly surprising new capabilities resulting from various synergetic interactions amongst both the family of ninety-two regenerative and the trans-uranium members of the uniquely-behaving chemical elements family.
+
+Complex environmental evolution is synergetically produced by the biologicals and their tools as well as by the great inanimate physiological complex of events such as earthquakes and storms which have constant challenging effect upon the individual biological inventiveness wherein both the challenges and the cause are regenerative. Our common wealth is also multiplied in further degree by experimentally-derived information which is both multiplying and integrating the wealth advantage at an exponential rate. The synergetic effect upon the rate of growth of our incipient world common wealth augmentation has been entirely overlooked throughout all the accounting systems of all the ideologically-divergent political systems. Our wealth is inherently common wealth and our common wealth can only increase, and it is increasing at a constantly self-accelerating synergetic rate.
+
+However, we inadvertently dip into our real, unaccountedly fabulous wealth in a very meager way only when our political leaders become scared enough by the challenge of an impressively threatening enemy. Then only do socialism and capitalism alike find that they have to afford whatever they need. The only limitation in the realization of further wealth is that production engineers must be able to envision and reduce to design and practice the production-multiplying steps to be taken, which progressive envisioning depends both on the individual and on the experimentally proven, but as yet untapped, state of the pertinent metaphysical arts, as well as upon the range of resources strategically available at the time and in particular upon the inventory of as yet unemployed but relevant inventions.
+
+In respect to physical resources, until recently man had assumed that he could produce his buildings, machinery, and other products only out of the known materials. From time to time in the past, scientists discovered new alloys which changed the production engineering prospects. But now in the aerospace technology man has developed his metaphysical capabilities to so advanced a degree that he is evolving utterly unique materials "on order." Those new materials satisfy the prespecified physical behavior characteristics which transcend those of any substance previously known to exist anywhere in the universe. Thus, the re-entry nose-cones of the man-launched and rocketed satellites were developed. Synergy is of the essence. Only under the stresses of total social emergencies as thus far demonstrated by man do the effectively adequate alternative technical strategies synergetically emerge. Here we witness mind over matter and humanityâs escape from the limitations of his exclusive identity only with some sovereignized circumscribed geographical locality.
+
+7. integral functions
+
+The first census of population in the United States was taken in 1790. In I8IO the United States Treasury conducted the first economic census of the young democracy. There were at that time one million families in this country. There were also one million human slaves. This did not mean that each family had a human slave; far from it. The slaves were owned by relatively few.
+
+The Treasury adjudged the monetary value of the average American homestead, lands, buildings, furnishings, and tools to be worth sum-totaIly $350 per family. The Treasury appraised the average worth of each slave as $400. It was estimated that the wilderness hinterlands of America were worth $1,500 per family. The foregoing assets plus the canals and toll roads brought the equity of each family to a total of $3,000. This made the national wealth of the United States, as recognized by man, worth three billion dollars.
+
+Let us assume that, practicing supreme wisdom, the united American citizens of I8IO had convened their most reliably esteemed and farsighted leaders and had asked them to undertake a 150-year, grand economic and technical plan for most effectively and swiftly developing Americaâs and the worldâs life-support system-to be fully realized by 1960. At that time, it must be remembered, the telegraph had not been invented. There were no electro-magnetics or mass-produced steel. Railroads were as yet undreamed of, let alone wireless, X-ray, electric light, power by wire and electric motors. There was no conception of the periodic table of the atoms or of the existence of an electron. Had any of our forefathers committed our wealth of I8IO toward bouncing radar impulses off the Moon he would have been placed in a lunatic asylum.
+
+Under those I8IO circumstances of an assumed capital wealth of the united American states, both public and private, amounting to only three billion dollars, it is preposterous to think of humanityâs most brilliant and powerful leaders electing to invest their "all" of three billion dollars in a "thousand times more expensive" ten-trillion-dollar adventure such, however, as has since transpired, but only under the war-enforced threat of disintegration of the meager rights won thus far by common man from history-long tyrannical powers of a techno-illiterate and often cruel few.
+
+In I8IO it was also unthinkable by even the most brilliant leaders of humanity that I60 years hence, in 1970, the gross national product of the United States would reach one trillion dollars per year. (This is to be compared with the meager forty billion of the worldâs total monetary gold supply.) Assuming a 10 per cent rate of earnings, this 1970 trillion-dollar product would mean that a capital base of ten trillion dollars was operative within the United States alone where the 18IO national leaders had accredited only three billion dollars of national assets. The wisest humans recognized in I8IO only one three-hundredth of I per cent of the immediately thereafter "proven value" of the United Statesâ share of the worldâs wealth-generating potentials. Of course, those wisest men of the times would have seen little they could afford to do.
+
+Our most reliable, visionary, and well-informed great-grandfathers of I8IO could not have foreseen that in the meager century and one-half of all the billionsfold greater reaches of known universal time that human life-span would be trebled, that the yearly real income of the individual would be "enfolded, that the majority of diseases would be banished, and human freedom of realized travel one-hundred-folded; that humans would be able to whisper effortlessly in one anotherâs ear from anywhere around the world apart and at a speed of seven hundred million miles an hour, their audibility clearly reaching to the planet Venus; and that human vision around Earthâs spherical deck would be increased to see local pebbles and grains of sand on the moon.
+
+Now in 1969, 99.9 per cent of the accelerating accelerations of the physical environment changes effecting all humanityâs evolution are transpiring in the realms of the electromagnetic spectrum realities which are undetectable directly by the human senses. Because they are gestating invisibly it is approximately impossible for world society to comprehend that the changes in the next thirty-five years-ushering in the twenty-first century-will be far greater than in our just completed century and one-half since the first United States economic census. We are engulfed in an invisible tidal wave which, as it draws away, will leave humanity, if it survives, cast up upon an island of universal success uncomprehending how it has all happened.
+
+But we can scientifically assume that by the twenty-first century either humanity will not be living aboard Spaceship Earth or, if approximately our present numbers as yet remain aboard, that humanity then will have recognized and organized itself to realize effectively the fact that humanity can afford to do anything it needs and wishes to do and that it cannot afford anything else. As a consequence Earth-planet-based humanity will be physically and economically successful and individually free in the most important sense. While all enjoy total Earth no human will be interfering with the other, and none will be profiting at the expense of the other. Humans will be free in the sense that 99.9 per cent of their waking hours will be freely investable at their own discretion. They will be free in the sense that they will not struggle for survival on a `âyou" or "me" basis, and will therefore be able to trust one another and be free to co-operate in spontaneous and logical ways.
+
+It is also probable that during that one-third of a century of the curtain raising of the twenty-first century that the number of boo-booâs, biased blunders, short-sighted misjudgments, opinionated self-deceits of humanity will total, at minimum, six hundred trillion errors. Clearly, man will have backed into his future while evolution, operating as inexorably as fertilized ovaries gestate in the womb, will have brought about his success in ways as synergetically unforeseeable to us today as were the ten-trillion-dollar developments of the last I50 years unforeseen by our wisest great-grandfathers of 1810.
+
+All of this does not add up to say that man is stupidly ignorant and does not deserve to prosper. It adds up to the realization that in the design of universal evolution man was given an enormous safety factor as an economic cushion, within which to learn by trial and error to dare to use his most sensitively intuited intellectual conceptioning and greatest vision in joining forces with all of humanity to advance into the future in full accreditation of the individual human intellectâs most powerfully loving conceptions of the potential functioning of man in universe. All the foregoing is to say also that the opinions of any negatively conditioned reflexes regarding what I am saying and am about to say are unrealistically inconsequential.
+
+I have so far introduced to you a whole new synergetic assessment of wealth and have asked that you indicate your disagreement if you detected fallacies in the progressively-stated concepts of our common wealth. Thus we have discovered together that we are unanimous in saying that we can afford to do anything we need or wish to do.
+
+It is utterly clear to me that the highest priority need of world society at the present moment is a realistic economic accounting system which will rectify, for instance, such nonsense as the fact that a top toolmaker in India, the highest paid of all craftsmen, gets only as much per month for his work in India as he could earn per day for the same work if he were employed in Detroit, Michigan. How can India develop a favorable trade balance under those circumstances? If it canât have a workable, let alone favorable balance, how can these half-billion people participate in world intercourse? Millions of Hindus have never heard of America, let alone the international monetary system. Said Kipling "East is east and west is west and never the twain shall meet."
+
+As a consequence of the Great Piratesâ robbing Indo-China for centuries and cashing in their booty in Europe, so abysmally impoverished, underfed and physically afflicted have Indiaâs and Ceylonâs billions of humans been throughout so many centuries that it is their religious belief that life on Earth is meant to be exclusively a hellish trial and that the worse the conditions encountered by the individual the quicker his entry into heaven. For this reason attempts to help India in any realistic way are looked upon by a vast number of Indiaâs population as an attempt to prevent their entry into heaven. All this because they have had no other way to explain lifeâs hopelessness. On the other hand, they are extremely capable thinkers, and free intercourse with the world could change their views and fate. It is paradoxical that Indiaâs population should starve as one beef cattle for every three people wander through Indiaâs streets, blocking traffic as sacred symbols of nonsense. Probably some earlier conquerors intent to reserve the animals for their exclusive consumption as did later the kings of European nations decreed that God had informed the king that he alone was to eat animal meat and therefore God forbade the common people under penalty of death from killing a beef cattle for their own consumption.
+
+One of the myths of the moment suggest that wealth comes from individual bankers and capitalists. This concept is manifest in the myriad of charities that have to beg for alms for the poor, disabled, and helpless young and old in general. These charities are a hold-over from the old pirate days, when it was thought that there would never be enough to go around. They also are necessitated by our working assumption that we cannot afford to take care of all the helpless ones. Counseled by our bankers, our politicians say we canât afford the warring and the great society, too. And because of the mythical concept that the wealth which is disbursed is coming from some magically-secret private source, no free and healthy individual wants that "hand out" from the other man, whoever he may be. Nor does the individual wish to be on the publicly degrading "dole" line.
+
+After World War II several million of our well-trained, healthiest young people came suddenly out of the military service. Because we had automated during the war to a very considerable degree to meet the "war challenges" there were but few jobs to offer them. Our society could not say realistically that the millions of their healthiest, best informed young were unfit because they couldnât get a job, which had until that historical moment been the criteria of demonstrated fitness in Darwinâs "survival only of the fittest" struggle. In that emergency we legislated the GI Bill and sent them all to schools, colleges, and universities. This act was politically rationalized as a humanly dignified fellowship reward of their war service and not as a "hand out." It produced billions of dollars of new wealth through the increased know-how and intelligence thus released, which synergetically augmented the spontaneous initiative of that younger generation. In legislating this "reckless spending" of wealth we didnât know that we had produced a synergetic condition that would and did open the greatest prosperity humanity has ever known.
+
+Through all pre-twentieth century history wars were devastating to both winners and losers. The pre-industrial wars took the men from the fields, and the fields where the exclusively agricultural-wealth germinated, were devastated. It came as a complete surprise, therefore, that the first World War, which was the first full-fledged industrial-era war, ended with the United States in particular but Germany, England, France, Belgium, Italy, Japan, and Russia in lesser degree all coming out of the war with much greater industrial production capabilities than those with which they had entered. That wealth was soon misguidedly invested in the second World War, from which all the industrial countries emerged with even greater wealth producing capabilities, despite the superficial knockdown of the already obsolete buildings. It was irrefutably proven that the destruction of the buildings by bombing, shell fire, and flames left the machinery almost unharmed. The productive tooling capabilities multiplied unchecked, as did their value.
+
+This unexpected increase in wealth by industrial world wars was caused by several facts, but most prominently by the fact that in the progressive acquisition of instruments and tools which produce the even more effective complex of industrial tools, the number of special purpose tools that made the end-product armaments and ammunition was negligible in comparison with the redirectable productivity of the majority of the general-purpose tools that constituted the synergistic tool complex. Second, the wars destroyed the obsolete tool-enclosing brick-and-wood structures whose factual availability, despite their obsolescence, had persuaded their owners to over extend the structuresâ usefulness and exploitability. This drive to keep milking the old proven cow not risking the production of new cows had blocked the acquisition of up-to-date tools. Third, there was the synergetic surprise of alternative or "substitute" technologies which were developed to bypass destroyed facilities. The latter often proved to be more efficient than the tools that were destroyed. Fourth, the metals themselves not only were not destroyed but were acceleratingly reinvested in new, vastly higher-performance per pound tools. It was thus that the world war losers such as Germany and Japan became overnight the postwar industrial winners. Their success documented the fallacy of the whole economic evaluation system now extant.
+
+Thus again we see that, through gradually increasing use of his intuition and intellect, man has discovered many of the generalized principles that are operative in the universe and has employed them objectively but separately in extending his internal metabolic regeneration by his invented and detached tool extensions and their remote operation affected by harnessing inanimate energy. Instead of trying to survive only with his integral set of tool capabilities-his hands-to pour water into his mouth, he invents a more effective wooden, stone, or ceramic vessel so that he not only can drink from it but carry water with him and extend his hunting and berry picking. All tools are externalizations of originally integral functions. But in developing each tool man also extends the limits of its usefulness, since he can make bigger cups hold liquids too hot or chemically destructive for his hands. Tools do not introduce new principles but they greatly extend the range of conditions under which the discovered control principle may be effectively employed by man. There is nothing new in world technologyâs growth. It is only the vast increase of its effective ranges that are startling man. The computer is an imitation human brain. There is nothing new about it, but its capacity, speed of operation, and tirelessness, as well as its ability to operate under environmental conditions intolerable to the human anatomy, make it far more effective in performing special tasks than is the skull and tissue encased human brain, minus the computer.
+
+What is really unique about man is the magnitude to which he has detached, deployed, amplified, and made more incisive all of his many organic functionings. Man is unique among all the living phenomena as the most adaptable omni-environment penetrating, exploring, and operating organism being initially equipped to invent intellectually and self-disciplined, dexterously, to make the tools with which thus to extend himself. The bird, the fish, the tree are all specialized, and their special capability-functioning tools are attached integrally with their bodies, making them incapable of penetrating hostile environments. Man externalizes, separates out, and increases each of his specialized function capabilities by inventing tools as soon as he discovers the need through oft-repeated experiences with unfriendly environmental challenges. Thus, man only temporarily employs his integral equipment as a specialist, and soon shifts that function to detached tools. Man cannot compete physically as a muscle and brained automatonâas a machineâagainst the automated power tools which he can invent while metaphysically mastering the energy income from universe with which evermore powerfully to actuate these evermore precise mass-production tools. What man has done is to decentralize his functions into a world-around-energy-networked complex of tools which altogether constitute what we refer to as world industrialization.
+
+8. the regenerative landscape
+
+Thus man has developed an externalized metabolic regeneration organism involving the whole of Spaceship Earth and all its resources. Any human being can physically employ that organism, whereas only one human can employ the organically integral craft tool. All 9I of the 92 chemical elements thus far found aboard our spaceship are completely involved in the world-around industrial network. The full family of chemical elements is unevenly distributed, and therefore our total planet is at all times involved in the industrial integration of the unique physical behaviors of each of all the elements. Paradoxically, at the present moment our Spaceship Earth is in the perilous condition of having the Russians sitting at one set of the co-pilotâs flying controls while the Americans sit at the other. France controls the starboard engines, and the Chinese control the port engines, while the United Nations controls the passenger operation. The result is an increasing number of U. F. O. hallucinations of sovereign states darting backwards and forwards and around in circles, getting nowhere, at an incredibly accelerating rate of speed.
+
+All of humanityâs tool extensions are divisible into two main groups: the craft and the industrial tools. I define the craft tools as all those tools which could be invented by one man starting all alone, naked in the wilderness, using only his own experience and his own integral facilities. Under these isolated conditions he could and did invent spears, slings, bows, and arrows, etc. By industrial tools I mean all the tools that cannot be produced by one man, as for instance the S.S. Queen Mary. With this definition, we find that the spoken word, which took a minimum of two humans to develop, was the first industrial tool. It brought about the progressive integration of all individual generation-to-generation experiences and thoughts of all humanity everywhere and everywhen. The Bible says, "In the beginning was the word"; I say to you, "In the beginning of industrialization was the spoken word." With the graphic writing of the words and ideas we have the beginning of the computer, for the computer stores and retrieves information. The written word, dictionary and the book were the first information storing and retrieving systems.
+
+The craft tools are used initially by man to make the first industrial tools. Man is using his hands today most informatively and expertly only to press the buttons that set in action the further action of the tools which reproduce other tools which may be used informatively to make other tools. In the craft economies craftsman artists make only end- or consumer-products. In the industrial economy the craftsman artists make the tools and the tools make the end- or consumer-products. In this industrial development the mechanical advantages of men are pyramided rapidly and synergetically into invisible magnitudes of ever more incisive and inclusive tooling which produces ever more with ever less resource investment per each unit of end-product, or service, performance.
+
+As we study industrialization, we see that we cannot have mass production unless we have mass consumption. This was effected evolutionarily by the great social struggles of labor to increase wages and spread the benefits and prevent the reduction of the numbers of workers employed. The labor movement made possible mass purchasing; ergo, mass production; ergo, low prices on vastly improved products and services, which have altogether established entirely new and higher standards of humanityâs living.
+
+Our labor world and all salaried workers, including school teachers and college professors, are now, at least subconsciously if not consciously, afraid that automation will take away their jobs. They are afraid they wonât be able to do what is called "earning a living," which is short for earning the right to live. This term implies that normally we are supposed to die prematurely and that it is abnormal to be able to earn a living. It is paradoxical that only the abnormal or exceptional are entitled to prosper. Yesterday the term even inferred that success was so very abnormal that only divinely ordained kings and nobles were entitled to eat fairly regularly.
+
+It is easy to demonstrate to those who will take the time and the trouble to unbias their thoughts that automation swiftly can multiply the physical energy part of wealth much more rapidly and profusely than can manâs muscle and brain-reflexed-manually-controlled production. On the other hand humans alone can foresee, integrate, and anticipate the new tasks to be done by the progressively automated wealth-producing machinery. To take advantage of the fabulous magnitudes of real wealth waiting to be employed intelligently by humans and unblock automationâs postponement by organized labor we must give each human who is or becomes unemployed a life fellowship in research and development or in just simple thinking. Man must be able to dare to think truthfully and to act accordingly without fear of losing his franchise to live. The use of mind fellowships will permit humans comprehensively to expand and accelerate scientific exploration and experimental prototype development. For every 100,OOO employed in research and development, or just plain thinking, one probably will make a breakthrough that will more than pay for the other 99,999 fellowships. Thus, production will no longer be impeded by humans trying to do what machines can do better. Contrariwise, omni-automated and inanimately powered production will unleash humanityâs unique capability-its metaphysical capability. Historically speaking, these steps will be taken within the next decade. There is no doubt about it. But not without much social crisis and consequent educational experience and discovery concerning the nature of our unlimited wealth.
+
+Through the universal research and development fellowships, weâre going to start emancipating humanity from being muscle and reflex machines. Weâre going to give everybody a chance to develop their most powerful mental and intuitive faculties. Given their research and development fellowship, many who have been frustrated during their younger years may feel like going fishing. Fishing provides an excellent opportunity to think clearly; to review oneâs life; to recall oneâs earlier frustrated and abandoned longings and curiosities. What we want everybody to do is to think clearly.
+
+We soon will begin to generate wealth so rapidly that we can do very great things. I would like you to think what this may do realistically for living without spoiling the landscape, or the antiquities or the trails of humanity throughout the ages, or despoiling the integrity of romance, vision, and harmonic creativity. All the great office buildings will be emptied of earned living workers, and the automated office-processing of information will be centralized in the basements of a few buildings. This will permit all the modernly mechanized office buildings to be used as dwelling facilities.
+
+When we approach our problems on a universal, general systems basis and progressively eliminate the irrelevancies, somewhat as we peel petals from an artichoke, at each move we leave in full visibility the next most important layer of factors with which we must deal. We gradually uncover you and me in the heart of now. But evolution requires that we comprehend each layer in order to unpeel it. We have now updated our definitions of universe by conforming them with the most recent and erudite scientific findings such as -those of Einstein and Planck. Earlier in our thinking we discovered manâs function in universe to be that of the most effective metaphysical capability experimentally evidenced thus far within our locally observable phases and time zones of universe. We have also discovered that it is humanityâs task to comprehend and set in order the special case facts of human experience and to win therefrom knowledge of the a priori existence of a complex of generalized, abstract principles which apparently altogether govern all physically evolving phenomena of universe.
+
+We have learned that only and exclusively through use of his mind can man inventively employ the generalized principles further to conserve the locally available physical energy of the only universally unlimited supply. Only thus can man put to orderly advantage the various, local, and otherwise disorderly behaviors of the entropic, physical universe. Man can and may metaphysically comprehend, anticipate, shunt, and meteringly introduce the evolutionarily organized environment events in the magnitudes and frequencies that best synchronize with the patterns of his successful and metaphysical metabolic regeneration while ever increasing the degrees of humanityâs space and time freedoms from yesterdayâs ignorance sustaining survival procedure chores and their personal time capital wasting.
+
+Now we have comprehended and peeled off the layers of petals which disclosed not only that physical energy is conserved but also that it is ever increasingly deposited as a fossil-fuel savings account aboard our Spaceship Earth through photosynthesis and progressive, complex, topsoil fossilization buried ever deeper within Earthâs crust by frost, wind, flood, volcanoes, and earthquake upheavals. We have thus discovered also that we can make all of humanity successful through scienceâs world-engulfing industrial evolution provided that we are not so foolish as to continue to exhaust in a split second of astronomical history the orderly energy savings of billions of yearsâ energy conservation aboard our Spaceship Earth. These energy savings have been put into our Spaceshipâs life-regeneration-guaranteeing bank account for use only in self-starter functions.
+
+The fossil fuel deposits of our Spaceship Earth correspond to our automobileâs storage battery which must be conserved to turn over our main engineâs self-starter. Thereafter, our "main engine," the life regenerating processes, must operate exclusively on our vast daily energy income from the powers of wind, tide, water, and the direct Sun radiation energy. The fossil-fuel savings account has been put aboard Spaceship Earth for the exclusive function of getting the new machinery built with which to support life and humanity at ever more effective standards of vital physical energy and reinspiring metaphysical sustenance to be sustained exclusively on our Sun radiationâs and Moon pull gravityâs tidal, wind, and rainfall generated pulsating and therefore harnessable energies. The daily income energies are excessively adequate for the operation of our main industrial engines and their automated productions. The energy expended in one minute of a tropical hurricane equals the combined energy of all the U.S.A. and U.S.S.R. nuclear weapons. Only by understanding this scheme may we continue for all time ahead to enjoy and explore universe as we progressively harness evermore of the celestially generated tidal and storm generated wind, water, and electrical power concentrations. We cannot afford to expend our fossil fuels faster than we are "recharging our battery," which means precisely the rate at which the fossil fuels are being continually deposited within Earthâs spherical crust.
+
+We have discovered that it is highly feasible for all the human passengers aboard Spaceship Earth to enjoy the whole ship without any individual interfering with another and without any individual being advantaged at the expense of another, provided that we are not so foolish as to burn up our ship and its operating equipment by powering our prime operations exclusively on atomic reactor generated energy. The too-shortsighted and debilitating exploitation of fossil fuels and atomic energy are similar to running our automobiles only on the self-starters and batteries and as the latter become exhausted replenishing the batteries only by starting the chain reaction consumption of the atoms with which the automobiles are constituted.
+
+We have discovered also why we were given our intellectual faculties and physical extension facilities. We have discovered that we have the inherent capability and inferentially the responsibility of making humanity comprehensively and sustainably successful. We have learned the difference between brain and mind capabilities. We have learned of the superstitions and inferiority complexes built into all humanity through all of historyâs yesterdays of slavish survival under conditions of abysmal illiteracy and ignorance wherein only the most ruthless, shrewd, and eventually brutish could sustain existence, and then for no more than a third of its known potential life span.
+
+This all brings us to a realization of the enormous educational task which must be successfully accomplished right now in a hurry in order to convert manâs spin-dive toward oblivion into an intellectually mastered power pullout into safe and level flight of physical and metaphysical success, whereafter he may turn his Spaceship Earthâs occupancy into a universe exploring advantage. If it comprehends and reacts effectively, humanity will open an entirely new chapter of the experiences and the thoughts and drives thereby stimulated.
+
+Most importantly we have learned that from here on it is success for all or for none, for it is experimentally proven by physics that "unity is plural and at minimum two"âthe complementary but not mirror-imaged proton and neutron. You and I are inherently different and complementary. Together we average as zero-that is, as eternity.
+
+Now having attained that cosmic degree of orbital conceptioning we will use our retrorocket controls to negotiate our reentry of our Spaceship Earthâs atmosphere and return to our omni-befuddled present. Here we find ourselves maintaining the fiction that our crossbreeding World Man consists fundamentally of innately different nations and races which are the antithesis of that crossbreeding. Nations are products of many generations of local in-breeding in a myriad of remote human enclaves. With grandfather chiefs often marrying incestuously the gene concentrations brought about hybrid nationally-unique physiological characteristics which in the extreme northern hibernations bleached out the human skin and in the equatorial casting off of all clothing inbred darkly tanned pigmentation. All are the consequence only of unique local environment conditions and super inbreeding.
+
+The crossbreeding world people on the North American continent consist of two separate input sets. The first era input set consists of those who came with the prevailing winds and ocean currents eastward to the North, South, and Central Americas by raft and by boat from across the Pacific, primarily during an age which started at least thirty thousand years ago, possibly millions of years ago, and terminated three hundred years ago. The eastbound trans-Pacific migration peopled the west coasts of both South and North America and migrated inland towards the two continentsâ middle ground in Central America and Mexico. In Mexico today will be found every type of human characteristic and every known physiognomy, each of which occur in such a variety of skin shades from black to white that they do not permit the ignorance-invented "race" distinctions predicated only superficially on extreme limits of skin color. The second or westbound input era set of crossbreeding world man now peopling the Americas consists of the gradual and slower migration around the world from the Pacific Ocean westward into the wind, "following the sun," and travelling both by sea through Malaysia, across the Indian Ocean up the Persian Gulf into Mesopotamia and overland into the Mediterranean, up the Nile from East Africa into the South and North Atlantic to America-or over the Chinese, Mongolian, Siberian, and European hinterlands to the Atlantic and to the Americas.
+
+Now both east and westbound era sets are crossbreeding with one another in ever-accelerating degree on Americaâs continental middleground. This omni reintegration of world man from all the diverse hybrids is producing a crossbred people on the Pacific Coast of North America. Here with its aerospace and oceans penetrating capabilities, a world type of humanity is taking the springboard into all of the hitherto hostile environments of universe into the ocean depths and into the sky and all around the Earth.
+
+Returning you again to our omni-befuddled present, we realize that reorganization of humanityâs economic accounting system and its implementation of the total commonwealth capability by total world society, aided by the computerâs vast memory and high speed recall comes first of all of the first-things-first that we must attend to to make our space vehicle Earth a successful man operation. We may now raise our sights, in fact must raise our sights, to take the initiative in planning the world-around industrial retooling revolution. We must undertake to increase the performance per pound of the worldâs resources until they provide all of humanity a high standard of living. We can no longer wait to see whose biased political system should prevail over the world.
+
+You may not feel very confident about how you are going to earn your right to live under such world-around patron-less conditions. But I say to you the sooner you do the better chance we have of pulling out of humanityâs otherwise fatal nose dive into oblivion. As the world political economic emergencies increase, remember that we have discovered a way to make the total world work. It must be initiated and in strong momentum before we pass the point of no return. You may gain great confidence from the fact that your fellow men, some of them your great labor leaders, are already aware and eager to educate their own rank and file on the fallacy of opposition to automation.
+
+I have visited more than three hundred universities and colleges around the world as an invited and appointed professor and have found an increasing number of students who understand all that we have been reviewing. They are comprehending increasingly that elimination of war can only be realized through a design and invention revolution. When it is realized by society that wealth is as much everybodyâs as is the air and sunlight, it no longer will be rated as a personal handout for anyone to accept a high standard of living in the form of an annual research and development fellowship.
+
+I have owned successively, since boyhood, fifty-four automobiles. I will never own another. I have not given up driving. I began to leave my cars at airports-never or only infrequently getting back to them. My new pattern requires renting new cars at the airports as needed. I am progressively ceasing to own things, not on a political-schism basis, as for instance Henry Georgeâs ideology, but simply on a practical basis. Possession is becoming progressively burdensome and wasteful and therefore obsolete.
+
+Why accumulate mementos of far away places when you are much more frequently in those places than at your yesterdayâs home, nation, state, city, and street identified residences, as required for passport, taxing, and voting functions? Why not completely restore the great cities and buildings of antiquity and send back to them all their fragmented treasures now deployed in the worldâs museums? Thus, may whole eras be reinhabited and experienced by an ever increasingly interested, well-informed, and inspired humanity. Thus, may all the world regain or retain its regenerative metaphysical mysteries.
+
+I travel between Southern and Northern hemispheres and around the world so frequently that I no longer have any so-called normal winter and summer, nor normal night and day, for I fly in and out of the shaded or sun-flooded areas of the spinning, orbiting Earth with ever-increased frequency. I wear three watches to tell me what time it is at my "home" office, so that I can call them by long distance telephone. One is set for the time of day in the place to which I am next going, and one is set temporarily for the locality in which I happen to be. I now see the Earth realistically as a sphere and think of it as a spaceship. It is big, but it is comprehensible. I no longer think in terms of "weeks" except as I stumble over their antiquated stop-and-go habits. Nature has no "weeks." Quite clearly the peak traffic patterns exploited by businessmen who are eager to make the most profit in order to prove their right to live causes everybody to go in and out of the airport during two short moments in the twenty-four hours with all the main facilities shut down two-thirds of the time. All our beds around the world are empty for two-thirds of the time. Our living rooms are empty seven-eighths of the time.
+
+The population explosion is a myth. As we industrialize, down goes the annual birth rate. If we survive, by 1985, the whole world will be industrialized, and, as with the United States, and as with all Europe and Russia and Japan today, the birth rate will be dwindling and the bulge in population will be recognized as accounted for exclusively by those who are living longer.
+
+When world realization of its unlimited wealth has been established there as yet will be room for the whole of humanity to stand indoors in greater New York City, with more room for each human than at an average cocktail party.
+
+We will oscillate progressively between social concentrations in cultural centers and in multi-deployment in greater areas of our Spaceship Earthâs as yet very ample accommodations. The same humans will increasingly converge for metaphysical intercourse and deploy for physical experiences.
+
+Each of our four billion humansâ shares of the Spaceship Earthâs resources as yet today amount to two-hundred billion tons.
+
+It is also to be remembered that despite the fact that you are accustomed to thinking only in dots and lines and a little bit in areas does not defeat the fact that we live in omnidirectional space-time and that a four dimensional universe provides ample individual freedoms for any contingencies.
+
+You may very appropriately want to ask me how we are going to resolve the ever-acceleratingly dangerous impasse of world-opposed politicians and ideological dogmas. I answer, it will be resolved by the computer. Man has ever-increasing confidence in the computer; witness his unconcerned landings as airtransport passengers coming in for a landing in the combined invisibility of fog and night. While no politician or political system can ever afford to yield understandably and enthusiastically to their adversaries and opposers, all politicians can and will yield enthusiastically to the computers safe flight-controlling capabilities in bringing all of humanity in for a happy landing.
+
+So, planners, architects, and engineers take the initiative. Go to work, and above all co-operate and donât hold back on one another or try to gain at the expense of another. Any success in such lopsidedness will be increasingly short-lived. These are the synergetic rules that evolution is employing and trying to make clear to us. They are not man-made laws. They are the infinitely accommodative laws of the intellectual integrity governing universe.
\ No newline at end of file
|
macbury/webpraca
|
0940ddff8c4abfbd22646ef6e93e184e7876227d
|
fixed gems dependency informations in project
|
diff --git a/Rakefile b/Rakefile
index 33bb184..3ae14c7 100644
--- a/Rakefile
+++ b/Rakefile
@@ -1,17 +1,21 @@
# Add your own tasks in files placed in lib/tasks ending in .rake,
# for example lib/tasks/capistrano.rake, and they will automatically be available to Rake.
require(File.join(File.dirname(__FILE__), 'config', 'boot'))
require 'rake'
require 'rake/testtask'
require 'rake/rdoctask'
require 'tasks/rails'
class Object
def verbose
$verbose = true
end
end
-require 'sitemap_generator/tasks' rescue LoadError
\ No newline at end of file
+
+
+unless ARGV.any? {|a| a =~ /^gems/} # Don't load anything when running the gems:* tasks
+ require 'sitemap_generator/tasks' rescue LoadError
+end
diff --git a/lib/tasks/webpraca.rake b/lib/tasks/webpraca.rake
index 9afcbcc..b0cd6d0 100644
--- a/lib/tasks/webpraca.rake
+++ b/lib/tasks/webpraca.rake
@@ -1,74 +1,79 @@
+unless ARGV.any? {|a| a =~ /^gems/} # Don't load anything when running the gems:* tasks
+
require 'highline/import'
+
def ask_for_password(message)
val = ask(message) {|q| q.echo = false}
if val.nil? || val.empty?
return ask_for_password(message)
else
return val
end
end
def ask(message)
puts "#{message}:"
val = STDIN.gets.chomp
if val.nil? || val.empty?
return ask(message)
else
return val
end
end
def render_errors(obj)
index = 0
obj.errors.each_full do |msg|
index += 1
puts "#{index}. #{msg}"
end
end
namespace :webpraca do
namespace :clear do
task :applicants => :environment do
Applicant.all.each(&:destroy)
end
task :visits => :environment do
Visit.all.each(&:destroy)
end
end
namespace :jobs do
task :remove_old => :environment do
Job.old.each(&:destroy)
end
task :publish_all => :environment do
Job.all(:conditions => { :published => false }).each do |job|
job.send_notification
job.publish!
end
end
task :publish => :environment do
Job.all(:conditions => { :published => nil }).each do |job|
job.publish!
end
end
end
namespace :admin do
task :create => :environment do
puts "Creating new admin user"
user = User.new
user.email = ask("Enter E-Mail")
user.password = ask_for_password("Enter Password")
user.password_confirmation = ask_for_password("Enter password confirmation")
if user.save
puts "Created admin user!"
else
render_errors(user)
end
end
end
-end
\ No newline at end of file
+end
+
+end
|
macbury/webpraca
|
d0934631724b8fe1c06bf4091ae39a1c17b0064c
|
fixed 'more' gem requirement
|
diff --git a/lib/tasks/more_tasks.rake b/lib/tasks/more_tasks.rake
index 32f320f..5ddd760 100644
--- a/lib/tasks/more_tasks.rake
+++ b/lib/tasks/more_tasks.rake
@@ -1,20 +1,24 @@
+unless ARGV.any? {|a| a =~ /^gems/} # Don't load anything when running the gems:* tasks
+
require 'less'
require 'more'
namespace :more do
desc "Generate CSS files from LESS files"
task :parse => :environment do
puts "Parsing files from #{Less::More.source_path}."
Less::More.parse
puts "Done."
end
desc "Remove generated CSS files"
task :clean => :environment do
puts "Deleting files.."
Less::More.clean
puts "Done."
end
end
+
+end
|
macbury/webpraca
|
2d78d882ec7752e08049c3d95ca2bfd9ebaa2ef6
|
added basic specs for framework, language, localization, applicant models; removed unused test/ directory and fixtures for specs (factory_girl in use)
|
diff --git a/spec/factories.rb b/spec/factories.rb
index 57138b7..15a4d3d 100644
--- a/spec/factories.rb
+++ b/spec/factories.rb
@@ -1,27 +1,42 @@
+Factory.sequence :email do |n|
+ "person#{n}@example.com"
+end
+
+
Factory.define :job do |f|
f.title { "Google CEO" }
# it's faster to fing existing record, than create new one
f.category { |c| Category.find(:first) || c.association(:category) }
f.localization { |l| Localization.find(:first) || l.association(:localization) }
f.type_id 0
f.description "You'll probably like this job."
f.company_name "Google"
f.email "google@google.com"
f.published true
f.availability_time 14
f.price_from 3000
f.price_to 4000
f.website "http://google.com/jobs"
f.regon "141066449"
f.nip "701-00-87-331"
f.krs "0000287684"
end
+Factory.define :applicant do |f|
+ f.email { Factory.next(:email) }
+ f.body "I am the boss"
+ f.job { |j| Job.find(:first) || j.association(:job) }
+ f.cv_file_name "lorem_cv.pdf"
+ f.cv_content_type "application/pdf"
+ f.cv_file_size 1024
+ f.token "f9ece2216c3e25961b1e7f0ed428f1bed0015f72"
+end
+
Factory.define :category do |f|
f.sequence(:name) {|n| "category #{n}" }
end
Factory.define :localization do |f|
f.name "Warszawa"
f.permalink "warszawa"
end
\ No newline at end of file
diff --git a/spec/fixtures/jobs.yml b/spec/fixtures/jobs.yml
deleted file mode 100644
index 5bf0293..0000000
--- a/spec/fixtures/jobs.yml
+++ /dev/null
@@ -1,7 +0,0 @@
-# Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html
-
-# one:
-# column: value
-#
-# two:
-# column: value
diff --git a/spec/models/applicant_spec.rb b/spec/models/applicant_spec.rb
new file mode 100644
index 0000000..a0757a2
--- /dev/null
+++ b/spec/models/applicant_spec.rb
@@ -0,0 +1,24 @@
+require 'spec_helper'
+
+
+describe Applicant do
+ it "should create a new instance given valid attributes" do
+ Factory.build(:applicant).save!
+ end
+
+ it "should generate unique token for new applicant" do
+ applicant = Factory.build(:applicant, :token => nil)
+ applicant.save!
+ applicant.token.should_not == nil
+
+ Factory.build(:applicant, :token => applicant.token).save!
+ applicant.class.find_by_token(applicant.token).should_not be_kind_of Array
+ end
+
+ it "should send e-mail to job's publisher for new applicant" do
+ applicant = Factory.build(:applicant)
+ applicant.should_receive(:send_email)
+ applicant.save!
+ end
+end
+
diff --git a/spec/models/framework_spec.rb b/spec/models/framework_spec.rb
new file mode 100644
index 0000000..c2d2258
--- /dev/null
+++ b/spec/models/framework_spec.rb
@@ -0,0 +1,14 @@
+require 'spec_helper'
+
+
+describe Framework do
+ it "should obtain all frameworks with theirs jobs count" do
+ job = Factory.build(:job)
+ job.save!
+
+ Framework.find_job_frameworks.each do |framework|
+ framework.jobs_count.should == "1" if framework == job.framework
+ end
+ end
+end
+
diff --git a/spec/models/language_spec.rb b/spec/models/language_spec.rb
new file mode 100644
index 0000000..8d527bb
--- /dev/null
+++ b/spec/models/language_spec.rb
@@ -0,0 +1,14 @@
+require 'spec_helper'
+
+
+describe Language do
+ it "should obtain all languages with theirs jobs count" do
+ job = Factory.build(:job)
+ job.save!
+
+ Language.find_job_languages.each do |language|
+ language.jobs_count.should == "1" if language == job.language
+ end
+ end
+end
+
diff --git a/spec/models/localization_spec.rb b/spec/models/localization_spec.rb
new file mode 100644
index 0000000..41894f7
--- /dev/null
+++ b/spec/models/localization_spec.rb
@@ -0,0 +1,14 @@
+require 'spec_helper'
+
+
+describe Localization do
+ it "should obtain all localizations with theirs jobs count" do
+ job = Factory.build(:job)
+ job.save!
+
+ Localization.find_job_localizations.each do |localization|
+ localization.jobs_count.should == "1" if localization == job.localization
+ end
+ end
+end
+
diff --git a/test/fixtures/languages.yml b/test/fixtures/languages.yml
deleted file mode 100644
index 88a5970..0000000
--- a/test/fixtures/languages.yml
+++ /dev/null
@@ -1,9 +0,0 @@
-# Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html
-
-one:
- name: MyString
- permalink: MyString
-
-two:
- name: MyString
- permalink: MyString
diff --git a/test/functional/admin/stats_controller_test.rb b/test/functional/admin/stats_controller_test.rb
deleted file mode 100644
index f09e4f8..0000000
--- a/test/functional/admin/stats_controller_test.rb
+++ /dev/null
@@ -1,8 +0,0 @@
-require 'test_helper'
-
-class Admin::StatsControllerTest < ActionController::TestCase
- # Replace this with your real tests.
- test "the truth" do
- assert true
- end
-end
diff --git a/test/unit/helpers/admin/stats_helper_test.rb b/test/unit/helpers/admin/stats_helper_test.rb
deleted file mode 100644
index 8336201..0000000
--- a/test/unit/helpers/admin/stats_helper_test.rb
+++ /dev/null
@@ -1,4 +0,0 @@
-require 'test_helper'
-
-class Admin::StatsHelperTest < ActionView::TestCase
-end
diff --git a/test/unit/language_test.rb b/test/unit/language_test.rb
deleted file mode 100644
index a366793..0000000
--- a/test/unit/language_test.rb
+++ /dev/null
@@ -1,8 +0,0 @@
-require 'test_helper'
-
-class LanguageTest < ActiveSupport::TestCase
- # Replace this with your real tests.
- test "the truth" do
- assert true
- end
-end
|
macbury/webpraca
|
10a93ab0c8426cbb81e489e782869572857084e6
|
normalized config file names (*.yml.example); moved plugin 'more' into gem dependency, so 'rake gems' will not crash if you haven't 'less' gem installed (rake tasks from 'more' are copied into lib/tasks/)
|
diff --git a/.gitignore b/.gitignore
index 14e813c..d5ed4b6 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,13 +1,17 @@
.DS_Store
log/*.log
tmp/**/*
public/*.xml.gz
+public/stylesheets/*
+public/javascripts/*
public/images/captchas/*
config/database.yml
config/mailer.yml
config/exception_notifer.yml
config/exception_notifier.yml
config/website_config.yml
config/micro_feed.yml
config/newrelic.yml
db/*.sqlite3
+nbproject
+coverage
diff --git a/config/database.yml.example b/config/database.yml.example
new file mode 100644
index 0000000..5916574
--- /dev/null
+++ b/config/database.yml.example
@@ -0,0 +1,51 @@
+# PostgreSQL. Versions 7.4 and 8.x are supported.
+#
+# Install the ruby-postgres driver:
+# gem install ruby-postgres
+# On Mac OS X:
+# gem install ruby-postgres -- --include=/usr/local/pgsql
+# On Windows:
+# gem install ruby-postgres
+# Choose the win32 build.
+# Install PostgreSQL and put its /bin directory on your path.
+development:
+ adapter: postgresql
+ encoding: unicode
+ database: webpraca_development
+ pool: 5
+ username: webpraca
+ password:
+
+ # Connect on a TCP socket. Omitted by default since the client uses a
+ # domain socket that doesn't need configuration. Windows does not have
+ # domain sockets, so uncomment these lines.
+ #host: localhost
+ #port: 5432
+
+ # Schema search path. The server defaults to $user,public
+ #schema_search_path: myapp,sharedapp,public
+
+ # Minimum log levels, in increasing order:
+ # debug5, debug4, debug3, debug2, debug1,
+ # log, notice, warning, error, fatal, and panic
+ # The server defaults to notice.
+ #min_messages: warning
+
+# Warning: The database defined as "test" will be erased and
+# re-generated from your development database when you run "rake".
+# Do not set this db to the same as development or production.
+test:
+ adapter: postgresql
+ encoding: unicode
+ database: webpraca_test
+ pool: 5
+ username: webpraca
+ password:
+
+production:
+ adapter: postgresql
+ encoding: unicode
+ database: webpraca_production
+ pool: 5
+ username: webpraca
+ password:
diff --git a/config/environment.rb b/config/environment.rb
index 5c4baae..c3833b1 100644
--- a/config/environment.rb
+++ b/config/environment.rb
@@ -1,51 +1,52 @@
# Be sure to restart your server when you modify this file
# Specifies gem version of Rails to use when vendor/rails is not present
# Bootstrap the Rails environment, frameworks, and default configuration
require File.join(File.dirname(__FILE__), 'boot')
Rails::Initializer.run do |config|
config.gem 'sitemap_generator', :lib => false, :source => 'http://gemcutter.org'
- config.gem 'less', :source => 'http://gemcutter.org', :lib => false
+ #config.gem 'less', :source => 'http://gemcutter.org', :lib => false
+ config.gem 'more', :source => 'http://gemcutter.org', :lib => false
config.gem 'meta-tags', :lib => 'meta_tags', :source => 'http://gemcutter.org'
config.gem 'declarative_authorization'
config.gem 'searchlogic'
config.gem 'RedCloth', :lib => "redcloth"
config.gem 'authlogic'
config.gem 'whenever', :lib => false, :source => 'http://gemcutter.org/'
config.gem 'highline', :lib => false
config.gem "factory_girl", :lib => false
config.gem "faker", :lib => false
config.gem 'rspec', :lib => false, :version => '>=1.2.9'
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Add additional load paths for your own custom dirs
# config.load_paths += %W( #{RAILS_ROOT}/extras )
# Specify gems that this application depends on and have them installed with rake gems:install
# config.gem "bj"
# config.gem "hpricot", :version => '0.6', :source => "http://code.whytheluckystiff.net"
# config.gem "sqlite3-ruby", :lib => "sqlite3"
# config.gem "aws-s3", :lib => "aws/s3"
# Only load the plugins named here, in the order given (default is alphabetical).
# :all can be used as a placeholder for all plugins not explicitly named
#config.plugins = [ :all, :less, 'less-rails' ]
# Skip frameworks you're not going to use. To use Rails without a database,
# you must remove the Active Record framework.
# config.frameworks -= [ :active_record, :active_resource, :action_mailer ]
# Activate observers that should always be running
# config.active_record.observers = :cacher, :garbage_collector, :forum_observer
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names.
config.time_zone = 'Warsaw'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}')]
config.i18n.default_locale = :en
-end
\ No newline at end of file
+end
diff --git a/config/micro_feed.yml.example b/config/micro_feed.yml.example
new file mode 100644
index 0000000..2c1452f
--- /dev/null
+++ b/config/micro_feed.yml.example
@@ -0,0 +1,18 @@
+blip:
+ login: username
+ password: secret
+
+flaker:
+ login: username
+ password: secret
+
+pinger:
+ login: username
+ password: secret
+
+twitter:
+ login: username
+ password: secret
+
+spinacz:
+ hash: 139c82e0679b64132f528fa71a9ee8d1
\ No newline at end of file
diff --git a/vendor/plugins/more/tasks/more_tasks.rake b/lib/tasks/more_tasks.rake
similarity index 84%
rename from vendor/plugins/more/tasks/more_tasks.rake
rename to lib/tasks/more_tasks.rake
index 55fb4bf..32f320f 100644
--- a/vendor/plugins/more/tasks/more_tasks.rake
+++ b/lib/tasks/more_tasks.rake
@@ -1,19 +1,20 @@
require 'less'
-require File.join(File.dirname(__FILE__), '..', 'lib', 'more')
+require 'more'
+
namespace :more do
desc "Generate CSS files from LESS files"
task :parse => :environment do
puts "Parsing files from #{Less::More.source_path}."
Less::More.parse
puts "Done."
end
desc "Remove generated CSS files"
task :clean => :environment do
puts "Deleting files.."
Less::More.clean
puts "Done."
end
-end
\ No newline at end of file
+end
diff --git a/vendor/plugins/more/MIT-LICENSE b/vendor/plugins/more/MIT-LICENSE
deleted file mode 100644
index 7e56959..0000000
--- a/vendor/plugins/more/MIT-LICENSE
+++ /dev/null
@@ -1,20 +0,0 @@
-Copyright (c) 2009 Logan Raarup, August Lilleaas
-
-Permission is hereby granted, free of charge, to any person obtaining
-a copy of this software and associated documentation files (the
-"Software"), to deal in the Software without restriction, including
-without limitation the rights to use, copy, modify, merge, publish,
-distribute, sublicense, and/or sell copies of the Software, and to
-permit persons to whom the Software is furnished to do so, subject to
-the following conditions:
-
-The above copyright notice and this permission notice shall be
-included in all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/vendor/plugins/more/README.markdown b/vendor/plugins/more/README.markdown
deleted file mode 100644
index aba362d..0000000
--- a/vendor/plugins/more/README.markdown
+++ /dev/null
@@ -1,138 +0,0 @@
-More
-====
-
-*LESS on Rails.*
-
-More is a plugin for Ruby on Rails applications. It automatically parses your applications `.less` files through LESS and outputs CSS files.
-
-In details, More does the following:
-
-* Recursively looks for LESS (`.less`) files in `app/stylesheets`
-* Ignores partials (prefixed with underscore: `_partial.less`) - these can be included with `@import` in your LESS files
-* Saves the resulting CSS files to `public/stylesheets` using the same directory structure as `app/stylesheets`
-
-LESS
-----
-
-LESS extends CSS with: variables, mixins, operations and nested rules. For more information, see [http://lesscss.org](http://lesscss.org).
-
-Upgrading from less-for-rails
-=======================================
-
-The old `less-for-rails` plugin looked for `.less` files in `public/stylesheets`. This plugin looks in `app/stylesheets`.
-
-To migrate, you can either set `Less::More.source_path = Rails.root + "/public/stylesheets"`, or move your `.less` files to `app/stylesheets`.
-
-
-Installation
-============
-
-More depends on the LESS gem. Please install LESS first:
-
- $ gem install less
-
-Rails Plugin
-------------
-
-Use this to install as a plugin in a Ruby on Rails app:
-
- $ script/plugin install git://github.com/cloudhead/more.git
-
-Rails Plugin (using git submodules)
------------------------------------
-
-Use this if you prefer to use git submodules for plugins:
-
- $ git submodule add git://github.com/cloudhead/more.git vendor/plugins/more
- $ script/runner vendor/plugins/more/install.rb
-
-
-Usage
-=====
-
-Upon installation, a new directory will be created in `app/stylesheets`. Any LESS file placed in this directory, including subdirectories, will
-automatically be parsed through LESS and saved as a corresponding CSS file in `public/stylesheets`. Example:
-
- app/stylesheets/clients/screen.less => public/stylesheets/clients/screen.css
-
-If you prefix a file with an underscore, it is considered to be a partial, and will not be parsed unless included in another file. Example:
-
- <file: app/stylesheets/clients/partials/_form.less>
- @text_dark: #222;
-
- <file: app/stylesheets/clients/screen.less>
- @import "partials/_form";
-
- input { color: @text_dark; }
-
-The example above will result in a single CSS file in `public/stylesheets/clients/screen.css`.
-
-Any `.css` file placed in `app/stylesheets` will be copied into `public/stylesheets` without being parsed through LESS.
-
-
-Configuration
-=============
-
-To set the source path (the location of your LESS files):
-
- Less::More.source_path = "/path/to/less/files"
-
-You can also set the destination path. Be careful with the formatting here, since this is in fact a route, and not a regular path.
-
- Less::More.destination_path = "css"
-
-More can compress your files by removing extra line breaks. This is enabled by default in the `production` environment. To change this setting, set:
-
- Less::More.compression = true
-
-More inserts headers in the generated CSS files, letting people know that the file is in fact generated and shouldn't be edited directly. This is by default only enabled in development mode. You can disable this behavior if you want to.
-
- Less::More.header = false
-
-To configure More for a specific environment, add configuration options into the environment file, such as `config/environments/development.rb`.
-
-If you wish to apply the configuration to all environments, place them in `config/environment.rb`.
-
-Heroku
-======
-
-The plugin works out-of-the-box on Heroku.
-
-Heroku has a read-only file system, which means caching the generated CSS with page caching is not an option. Heroku supports caching with Varnish, though, which the plugin will leverage by setting Cache-Control headers so that generated CSS is cached for one month.
-
-Tasks
-=====
-
-More provides a set of Rake tasks to help manage your CSS files.
-
-To parse all LESS files and save the resulting CSS files to the destination path, run:
-
- $ rake more:parse
-
-To delete all generated CSS files, run:
-
- $ rake more:clean
-
-This task will not delete any CSS files from the destination path, that does not have a corresponding LESS file in the source path.
-
-
-Git
-===
-
-If you are using git to version control your code and LESS for all your stylesheets, you can add this entry to your `.gitignore` file:
-
- public/stylesheets
-
-
-Documentation
-=============
-
-To view the full RDoc documentation, go to [http://rdoc.info/projects/cloudhead/more](http://rdoc.info/projects/cloudhead/more)
-
-
-Contributors
-============
-* August Lilleaas ([http://github.com/augustl](http://github.com/augustl))
-* Logan Raarup ([http://github.com/logandk](http://github.com/logandk))
-
-LESS is maintained by Alexis Sellier [http://github.com/cloudhead](http://github.com/cloudhead)
diff --git a/vendor/plugins/more/Rakefile b/vendor/plugins/more/Rakefile
deleted file mode 100644
index aee8009..0000000
--- a/vendor/plugins/more/Rakefile
+++ /dev/null
@@ -1,23 +0,0 @@
-require 'rake'
-require 'rake/testtask'
-require 'rake/rdoctask'
-
-desc 'Default: run unit tests.'
-task :default => :test
-
-desc 'Test the more plugin.'
-Rake::TestTask.new(:test) do |t|
- t.libs << 'lib'
- t.libs << 'test'
- t.pattern = 'test/**/*_test.rb'
- t.verbose = true
-end
-
-desc 'Generate documentation for the more plugin.'
-Rake::RDocTask.new(:rdoc) do |rdoc|
- rdoc.rdoc_dir = 'rdoc'
- rdoc.title = 'More'
- rdoc.options << '--line-numbers' << '--inline-source'
- rdoc.rdoc_files.include('README.markdown')
- rdoc.rdoc_files.include('lib/**/*.rb')
-end
diff --git a/vendor/plugins/more/app/controllers/less_cache_controller.rb b/vendor/plugins/more/app/controllers/less_cache_controller.rb
deleted file mode 100644
index 19a379d..0000000
--- a/vendor/plugins/more/app/controllers/less_cache_controller.rb
+++ /dev/null
@@ -1,22 +0,0 @@
-class LessCacheController < ApplicationController
- caches_page :show, :if => proc { Less::More.page_cache? }
- write_inheritable_attribute('filter_chain', FilterChain.new)
-
- def show
- path_spec = params[:id]
-
- if Less::More.exists?(params[:id])
- headers['Cache-Control'] = 'public; max-age=2592000' unless Less::More.page_cache? # Cache for a month.
- render :text => Less::More.generate(params[:id]), :content_type => "text/css"
- else
- render :nothing => true, :status => 404
- end
- end
-
- private
-
- # Don't log.
- def logger
- nil
- end
-end
\ No newline at end of file
diff --git a/vendor/plugins/more/config/routes.rb b/vendor/plugins/more/config/routes.rb
deleted file mode 100644
index d3ef2a0..0000000
--- a/vendor/plugins/more/config/routes.rb
+++ /dev/null
@@ -1,3 +0,0 @@
-ActionController::Routing::Routes.draw do |map|
- map.connect "#{Less::More.destination_path}/*id.css", :controller => 'less_cache', :action => "show"
-end
\ No newline at end of file
diff --git a/vendor/plugins/more/init.rb b/vendor/plugins/more/init.rb
deleted file mode 100644
index 6dbfa4c..0000000
--- a/vendor/plugins/more/init.rb
+++ /dev/null
@@ -1 +0,0 @@
-require File.join(File.dirname(__FILE__), 'rails', 'init')
diff --git a/vendor/plugins/more/install.rb b/vendor/plugins/more/install.rb
deleted file mode 100644
index 243033f..0000000
--- a/vendor/plugins/more/install.rb
+++ /dev/null
@@ -1,4 +0,0 @@
-require "fileutils"
-include FileUtils::Verbose
-
-mkdir_p File.join(Rails.root, "app", "stylesheets")
\ No newline at end of file
diff --git a/vendor/plugins/more/lib/more.rb b/vendor/plugins/more/lib/more.rb
deleted file mode 100644
index 11510ac..0000000
--- a/vendor/plugins/more/lib/more.rb
+++ /dev/null
@@ -1,177 +0,0 @@
-# Less::More provides methods for parsing LESS files in a rails application to CSS target files.
-#
-# When Less::More.parse is called, all files in Less::More.source_path will be parsed using LESS
-# and saved as CSS files in Less::More.destination_path. If Less::More.compression is set to true,
-# extra line breaks will be removed to compress the CSS files.
-#
-# By default, Less::More.parse will be called for each request in `development` environment and on
-# application initialization in `production` environment.
-
-begin
- require 'less'
-rescue LoadError => e
- e.message << " (You may need to install the less gem)"
- raise e
-end
-
-class Less::More
- DEFAULTS = {
- "production" => {
- :compression => true,
- :header => false,
- :destination_path => "stylesheets"
- },
- "development" => {
- :compression => false,
- :header => true,
- :destination_path => "stylesheets"
- }
- }
-
- HEADER = %{/*\n\n\n\n\n\tThis file was auto generated by Less (http://lesscss.org). To change the contents of this file, edit %s instead.\n\n\n\n\n*/}
-
- class << self
- attr_writer :compression, :header, :page_cache, :destination_path
-
- # Returns true if compression is enabled. By default, compression is enabled in the production environment
- # and disabled in the development and test environments. This value can be changed using:
- #
- # Less::More.compression = true
- #
- # You can put this line into config/environments/development.rb to enable compression for the development environments
- def compression?
- get_cvar(:compression)
- end
-
- # Check wether or not we should page cache the generated CSS
- def page_cache?
- (not heroku?) && page_cache_enabled_in_environment_configuration?
- end
-
- # For easy mocking.
- def page_cache_enabled_in_environment_configuration?
- Rails.configuration.action_controller.perform_caching
- end
-
- # Tells the plugin to prepend HEADER to all generated CSS, informing users
- # opening raw .css files that the file is auto-generated and that the
- # .less file should be edited instead.
- #
- # Less::More.header = false
- def header?
- get_cvar(:header)
- end
-
- # The path, or route, where you want your .css files to live.
- def destination_path
- get_cvar(:destination_path)
- end
-
- # Gets user set values or DEFAULTS. User set values gets precedence.
- def get_cvar(cvar)
- instance_variable_get("@#{cvar}") || (DEFAULTS[Rails.env] || DEFAULTS["production"])[cvar]
- end
-
- # Returns true if the app is running on Heroku. When +heroku?+ is true,
- # +page_cache?+ will always be false.
- def heroku?
- !!ENV["HEROKU_ENV"]
- end
-
- # Returns the LESS source path, see `source_path=`
- def source_path
- @source_path || Rails.root.join("app", "stylesheets")
- end
-
- # Sets the source path for LESS files. This directory will be scanned recursively for all *.less files. Files prefixed
- # with an underscore is considered to be partials and are not parsed directly. These files can be included using `@import`
- # statements. *Example partial filename: _form.less*
- #
- # Default value is app/stylesheets
- #
- # Examples:
- # Less::More.source_path = "/path/to/less/files"
- # Less::More.source_path = Pathname.new("/other/path")
- def source_path=(path)
- @source_path = Pathname.new(path.to_s)
- end
-
- # Checks if a .less or .lss file exists in Less::More.source_path matching
- # the given parameters.
- #
- # Less::More.exists?(["screen"])
- # Less::More.exists?(["subdirectories", "here", "homepage"])
- def exists?(path_as_array)
- return false if path_as_array[-1].starts_with?("_")
-
- pathname = pathname_from_array(path_as_array)
- pathname && pathname.exist?
- end
-
- # Generates the .css from a .less or .lss file in Less::More.source_path matching
- # the given parameters.
- #
- # Less::More.generate(["screen"])
- # Less::More.generate(["subdirectories", "here", "homepage"])
- #
- # Returns the CSS as a string.
- def generate(path_as_array)
- source = pathname_from_array(path_as_array)
-
- if source.extname == ".css"
- css = File.read(source)
- else
- engine = File.open(source) {|f| Less::Engine.new(f) }
- css = engine.to_css
- css.delete!("\n") if self.compression?
- css = (HEADER % [source.to_s]) << css if self.header?
- end
-
- css
- end
-
- # Generates all the .css files.
- def parse
- Less::More.all_less_files.each do |path|
- # Get path
- relative_path = path.relative_path_from(Less::More.source_path)
- path_as_array = relative_path.to_s.split(File::SEPARATOR)
- path_as_array[-1] = File.basename(path_as_array[-1], File.extname(path_as_array[-1]))
-
- # Generate CSS
- css = Less::More.generate(path_as_array)
-
- # Store CSS
- path_as_array[-1] = path_as_array[-1] + ".css"
- destination = Pathname.new(File.join(Rails.root, "public", Less::More.destination_path)).join(*path_as_array)
- destination.dirname.mkpath
-
- File.open(destination, "w") {|f|
- f.puts css
- }
- end
- end
-
- # Removes all generated css files.
- def clean
- all_less_files.each do |path|
- relative_path = path.relative_path_from(Less::More.source_path)
- css_path = relative_path.to_s.sub(/(le?|c)ss$/, "css")
- css_file = File.join(Rails.root, "public", Less::More.destination_path, css_path)
- File.delete(css_file) if File.file?(css_file)
- end
- end
-
- # Array of Pathname instances for all the less source files.
- def all_less_files
- Dir[Less::More.source_path.join("**", "*.{css,less,lss}")].map! {|f| Pathname.new(f) }
- end
-
- # Converts ["foo", "bar"] into a `Pathname` based on Less::More.source_path.
- def pathname_from_array(array)
- path_spec = array.dup
- path_spec[-1] = path_spec[-1] + ".{css,less,lss}"
- Pathname.glob(File.join(self.source_path.to_s, *path_spec))[0]
- end
- end
-end
diff --git a/vendor/plugins/more/more.gemspec b/vendor/plugins/more/more.gemspec
deleted file mode 100644
index 8dd1fd1..0000000
--- a/vendor/plugins/more/more.gemspec
+++ /dev/null
@@ -1,17 +0,0 @@
-
-require 'rake'
-
-SPEC = Gem::Specification.new do |s|
- s.name = "more"
- s.summary = "LESS on Rails"
- s.homepage = "http://github.com/cloudhead/more"
- s.description = <<-EOS
- More is a plugin for Ruby on Rails applications. It automatically
- parses your applications .less files through LESS and outputs CSS files.
- EOS
- s.authors = ["August Lilleaas", "Logan Raarup"]
- s.version = "0.0.4"
- s.files = FileList["README.markdown", "MIT-LICENSE", "Rakefile", "init.rb", "lib/*.rb", "rails/init.rb", "tasks/*", "test/*"]
- s.has_rdoc = true
- s.add_dependency "less"
-end
diff --git a/vendor/plugins/more/rails/init.rb b/vendor/plugins/more/rails/init.rb
deleted file mode 100644
index dc237bd..0000000
--- a/vendor/plugins/more/rails/init.rb
+++ /dev/null
@@ -1,6 +0,0 @@
-require File.join(File.dirname(__FILE__), '..', 'lib', 'more')
-
-config.after_initialize {
- Less::More.clean
- Less::More.parse if Less::More.page_cache?
-}
\ No newline at end of file
diff --git a/vendor/plugins/more/test/less_cache_controller_test.rb b/vendor/plugins/more/test/less_cache_controller_test.rb
deleted file mode 100644
index 31b9b12..0000000
--- a/vendor/plugins/more/test/less_cache_controller_test.rb
+++ /dev/null
@@ -1,41 +0,0 @@
-require 'test_helper'
-
-class LessCacheControllerTest < ActionController::IntegrationTest
- def setup
- Less::More.source_path = File.join(File.dirname(__FILE__), 'less_files')
- end
-
- test "regular stylesheet" do
- Less::More.expects(:page_cache_enabled_in_environment_configuration?).returns(true).at_least_once
- get "stylesheets/test.css"
- assert_response :success
- assert @response.body.include?("body { color: #222222; }")
- end
-
- test "sub-folder" do
- Less::More.expects(:page_cache_enabled_in_environment_configuration?).returns(true).at_least_once
- get "stylesheets/sub/test2.css"
- assert_response :success
- assert @response.body.include?("div { display: none; }")
- end
-
- test "plain css stylesheet" do
- Less::More.expects(:page_cache_enabled_in_environment_configuration?).returns(true).at_least_once
- get "stylesheets/plain.css"
- assert_response :success
- assert @response.body.include?("div { width: 1 + 1 }")
- end
-
- test "404" do
- Less::More.expects(:page_cache_enabled_in_environment_configuration?).returns(true)
- Less::More.expects(:generate).never
- get "stylesheets/does_not_exist.css"
- assert_response 404
- end
-
- test "setting headers with page cache" do
- Less::More.expects(:page_cache?).returns(false)
- get "stylesheets/test.css"
- assert @response.headers["Cache-Control"]
- end
-end
diff --git a/vendor/plugins/more/test/less_files/_global.less b/vendor/plugins/more/test/less_files/_global.less
deleted file mode 100644
index c99942a..0000000
--- a/vendor/plugins/more/test/less_files/_global.less
+++ /dev/null
@@ -1,2 +0,0 @@
-@text_light: #ffffff;
-@text_dark: #222222;
\ No newline at end of file
diff --git a/vendor/plugins/more/test/less_files/plain.css b/vendor/plugins/more/test/less_files/plain.css
deleted file mode 100644
index 72d5e00..0000000
--- a/vendor/plugins/more/test/less_files/plain.css
+++ /dev/null
@@ -1,2 +0,0 @@
-/* This file should not be parsed through LESS */
-div { width: 1 + 1 }
\ No newline at end of file
diff --git a/vendor/plugins/more/test/less_files/shared/_form.less b/vendor/plugins/more/test/less_files/shared/_form.less
deleted file mode 100644
index 3e0ceb1..0000000
--- a/vendor/plugins/more/test/less_files/shared/_form.less
+++ /dev/null
@@ -1,3 +0,0 @@
-.allforms {
- font-size: 110%;
-}
\ No newline at end of file
diff --git a/vendor/plugins/more/test/less_files/short.lss b/vendor/plugins/more/test/less_files/short.lss
deleted file mode 100644
index 5842517..0000000
--- a/vendor/plugins/more/test/less_files/short.lss
+++ /dev/null
@@ -1 +0,0 @@
-p { color:red; }
\ No newline at end of file
diff --git a/vendor/plugins/more/test/less_files/sub/test2.less b/vendor/plugins/more/test/less_files/sub/test2.less
deleted file mode 100644
index a33ed72..0000000
--- a/vendor/plugins/more/test/less_files/sub/test2.less
+++ /dev/null
@@ -1 +0,0 @@
-div { display:none; }
\ No newline at end of file
diff --git a/vendor/plugins/more/test/less_files/test.less b/vendor/plugins/more/test/less_files/test.less
deleted file mode 100644
index 008212f..0000000
--- a/vendor/plugins/more/test/less_files/test.less
+++ /dev/null
@@ -1,11 +0,0 @@
-@import "_global";
-@import "shared/_form";
-
-body {
- color: @text_dark;
-}
-
-form {
- .allforms;
- color: @text_light;
-}
\ No newline at end of file
diff --git a/vendor/plugins/more/test/more_test.rb b/vendor/plugins/more/test/more_test.rb
deleted file mode 100644
index bf7ed41..0000000
--- a/vendor/plugins/more/test/more_test.rb
+++ /dev/null
@@ -1,107 +0,0 @@
-require 'test_helper'
-
-class MoreTest < Test::Unit::TestCase
- def setup
- Less::More.class_eval do
- ["@compression", "@header"].each {|v|
- remove_instance_variable(v) if instance_variable_defined?(v)
- }
- end
- end
-
-
- def test_getting_config_from_current_environment_or_defaults_to_production
- Less::More::DEFAULTS["development"]["foo"] = 5
- Less::More::DEFAULTS["production"]["foo"] = 10
-
- Rails.expects(:env).returns("development")
- assert_equal 5, Less::More.get_cvar("foo")
-
- Rails.expects(:env).returns("production")
- assert_equal 10, Less::More.get_cvar("foo")
-
- Rails.expects(:env).returns("staging")
- assert_equal 10, Less::More.get_cvar("foo")
- end
-
- def test_user_settings_wins_over_defaults
- Less::More::DEFAULTS["development"][:compression] = true
- assert_equal true, Less::More.compression?
-
- Less::More::DEFAULTS["development"][:compression] = false
- assert_equal false, Less::More.compression?
-
- Less::More.compression = true
- assert_equal true, Less::More.compression?
- end
-
- def test_page_cache_is_read_from_environment_configs
- Less::More.expects(:heroku?).returns(false).times(2)
-
- Less::More.expects(:page_cache_enabled_in_environment_configuration?).returns(true)
- assert_equal true, Less::More.page_cache?
-
- Less::More.expects(:page_cache_enabled_in_environment_configuration?).returns(false)
- assert_equal false, Less::More.page_cache?
- end
-
- def test_page_cache_off_on_heroku
- Less::More.page_cache = true
- Less::More::DEFAULTS["development"][:page_cache] = true
-
- # The party pooper
- Less::More.expects(:heroku?).returns(true)
-
- assert_equal false, Less::More.page_cache?
- end
-
- def test_compression
- Less::More.compression = true
- assert_equal Less::More.compression?, true
-
- Less::More.compression = false
- assert_equal Less::More.compression?, false
- end
-
- def test_source_path
- Less::More.source_path = "/path/to/flaf"
- assert_equal Pathname.new("/path/to/flaf"), Less::More.source_path
- end
-
- def test_exists
- Less::More.source_path = File.join(File.dirname(__FILE__), 'less_files')
-
- assert Less::More.exists?(["test"])
- assert Less::More.exists?(["short"])
- assert Less::More.exists?(["sub", "test2"])
-
- # Partials does not exist
- assert !Less::More.exists?(["_global"])
- assert !Less::More.exists?(["shared", "_form"])
- end
-
- def test_generate
- Less::More.source_path = File.join(File.dirname(__FILE__), 'less_files')
- Less::More.compression = true
-
- assert Less::More.generate(["test"]).include?(".allforms { font-size: 110%; }body { color: #222222; }form { font-size: 110%; color: #ffffff;}")
- end
-
- def test_header
- Less::More.expects(:header?).returns(false)
- Less::More.source_path = File.join(File.dirname(__FILE__), 'less_files')
- assert !Less::More.generate(["test"]).starts_with?("/*")
-
- Less::More.expects(:header?).returns(true)
- Less::More.source_path = File.join(File.dirname(__FILE__), 'less_files')
- assert Less::More.generate(["test"]).starts_with?("/*")
- end
-
- def test_pathname_from_array
- Less::More.source_path = File.join(File.dirname(__FILE__), 'less_files')
-
- assert Less::More.pathname_from_array(["test"]).exist?
- assert Less::More.pathname_from_array(["short"]).exist?
- assert Less::More.pathname_from_array(["sub", "test2"]).exist?
- end
-end
diff --git a/vendor/plugins/more/test/test_helper.rb b/vendor/plugins/more/test/test_helper.rb
deleted file mode 100644
index c5d0786..0000000
--- a/vendor/plugins/more/test/test_helper.rb
+++ /dev/null
@@ -1,42 +0,0 @@
-require 'test/unit'
-
-require 'rubygems'
-require 'mocha'
-require 'active_support'
-require 'action_controller'
-
-ActionController::Base.session_store = nil
-
-module Rails
- extend self
-
- def env
- "development"
- end
-
- def root
- Pathname.new("/tmp")
- end
-
- def backtrace_cleaner
- ActiveSupport::BacktraceCleaner.new
- end
-end
-
-class ApplicationController < ActionController::Base
-end
-
-begin
- require 'less'
-rescue LoadError => e
- e.message << " (You may need to install the less gem)"
- raise e
-end
-
-require 'more'
-
-# Ugh.. shouldn't these be required for us?
-Dir.chdir("#{File.dirname(__FILE__)}/../") {
- require "config/routes"
- require 'app/controllers/less_cache_controller'
-}
\ No newline at end of file
|
macbury/webpraca
|
87d5863ae5b009a22a67e2c26cdc3ccea1a083e4
|
English version
|
diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb
index 93a9ab9..ba350a1 100644
--- a/app/controllers/application_controller.rb
+++ b/app/controllers/application_controller.rb
@@ -1,117 +1,134 @@
class ApplicationController < ActionController::Base
include ExceptionNotifiable
helper :all # include all helpers, all the time
protect_from_forgery # See ActionController::RequestForgeryProtection for details
filter_parameter_logging :password, :password_confirmation
helper_method :current_user_session, :current_user, :logged_in?, :own?
- before_filter :staging_authentication, :seo, :user_for_authorization
+ before_filter :set_locale, :staging_authentication, :seo, :user_for_authorization
def rescue_action_in_public(exception)
case exception
when ActiveRecord::RecordNotFound
render_404
when ActionController::RoutingError
render_404
when ActionController::UnknownController
render_404
when ActionController::UnknownAction
render_404
else
render_500
end
end
protected
+ def set_locale
+ I18n.locale = extract_locale_from_subdomain
+ end
+
+ def extract_locale_from_subdomain
+ redirect_to :subdomain => params[:locale] if params[:locale]
+
+ if ENV["RAILS_ENV"] == 'development'
+ parsed_locale = request.subdomains(0).first || '' #We do this for OS X in Development mode
+ else
+ parsed_locale = request.subdomains.first || ''
+ end
+
+ logger.debug "Language: #{parsed_locale}"
+ (AVAILABLE_LOCALES.include? parsed_locale) ? parsed_locale : WebSiteConfig['website']['default_language']
+ end
+
def render_404
@page_title = ["BÅÄ
d 404", "Nie znaleziono strony"]
render :template => "shared/error_404", :layout => 'application', :status => :not_found
end
def render_500
@page_title = ["BÅÄ
d 500", "CoÅ poszÅo nie tak"]
render :template => "shared/error_500", :layout => 'application', :status => :internal_server_error
end
def not_for_production
redirect_to root_path if Rails.env == "production"
end
# Ads Position
# :bottom, :right, :none
def self.ads_pos(position, options = {})
before_filter(options) do |controller|
controller.instance_variable_set('@ads_pos', position)
end
end
def user_for_authorization
Authorization.current_user = self.current_user
end
def permission_denied
flash[:error] = t('flash.error.access_denied')
redirect_to root_url
end
def seo
@ads_pos = :bottom
- set_meta_tags :description => WebSiteConfig['website']['description'],
- :keywords => WebSiteConfig['website']['tags']
+ set_meta_tags :description => t('head.description'),
+ :keywords => t('head.tags')
end
def staging_authentication
if ENV['RAILS_ENV'] == 'staging'
authenticate_or_request_with_http_basic do |user_name, password|
user_name == "change this" && password == "and this"
end
end
end
def current_user_session
@current_user_session ||= UserSession.find
return @current_user_session
end
def current_user
@current_user ||= self.current_user_session && self.current_user_session.user
return @current_user
end
def logged_in?
!self.current_user.nil?
end
def own?(object)
logged_in? && self.current_user.own?(object)
end
def store_location
session[:return_to] = request.request_uri
end
def redirect_back_or_default
redirect_to session[:return_to] || admin_path
session[:return_to] = nil
end
def login_required
unless logged_in?
respond_to do |format|
format.html do
flash[:error] = t('flash.error.access_denied')
store_location
redirect_to login_path
end
format.js { render :js => "window.location = #{login_path.inspect};" }
end
else
@page_title = [t('title.admin')]
end
end
end
\ No newline at end of file
diff --git a/app/controllers/jobs_controller.rb b/app/controllers/jobs_controller.rb
index ceae93f..b92dbdd 100644
--- a/app/controllers/jobs_controller.rb
+++ b/app/controllers/jobs_controller.rb
@@ -1,196 +1,196 @@
class JobsController < ApplicationController
validates_captcha :only => [:create, :new]
ads_pos :bottom
ads_pos :right, :except => [:home, :index, :search]
ads_pos :none, :only => [:home]
def home
set_meta_tags :title => t('home.title'),
:separator => " - "
query = Job.active.search
@recent_jobs = query.all(:order => "created_at DESC", :limit => 15, :include => [:localization, :category])
@top_jobs = query.all(:order => "rank DESC, created_at DESC", :limit => 15, :include => [:localization, :category])
end
# GET /jobs
# GET /jobs.xml
def index
@query = Job.active.search
options = {
:page => params[:page],
:per_page => 35,
:order => "created_at DESC, rank DESC",
:include => [:localization, :category]
}
if params[:order] =~ /popular/i
@page_title = [t('title.popular')]
@order = :rank
options[:order] = "rank DESC, created_at DESC"
else
@order = :created_at
@page_title = [t('title.latest')]
options[:order] = "created_at DESC, rank DESC"
end
if params[:language]
@language = Language.find_by_permalink!(params[:language])
@page_title << @language.name.downcase
@query.language_id_is(@language.id)
end
if params[:category]
@category = Category.find_by_permalink!(params[:category])
@page_title << @category.name.downcase
@query.category_id_is(@category.id)
end
if params[:localization]
@localization = Localization.find_by_permalink!(params[:localization])
@page_title << @localization.name.downcase
@query.localization_id_is(@localization.id)
end
if params[:framework]
@framework = Framework.find_by_permalink!(params[:framework])
@page_title << @framework.name.downcase
options[:include] << :framework
@query.framework_id_is(@framework.id)
end
if params[:type_id]
@type_id = JOB_TYPES.index(params[:type_id]) || 0
@page_title << JOB_TYPES[@type_id].downcase
@query.type_id_is(@type_id)
end
@jobs = @query.paginate(options)
respond_to do |format|
format.html # index.html.erb
format.rss
format.atom
end
end
def search
@page_title = [t('title.search')]
@search = Job.active.search(params[:search])
if params[:search]
@page_title = [t('title.finded_jobs')]
@jobs = @search.paginate( :page => params[:page],
:per_page => 30,
:order => "created_at DESC, rank DESC" )
end
respond_to do |format|
format.html
format.rss { render :action => "index" }
format.atom { render :action => "index" }
end
end
# GET /jobs/1
# GET /jobs/1.xml
def show
@job = Job.find_by_permalink!(params[:id])
@job.visited_by(request.remote_ip)
@category = @job.category
@page_title = [t('title.jobs'), @job.category.name.downcase, @job.localization.name.downcase, @job.company_name.downcase, @job.title.downcase]
- @tags = WebSiteConfig['website']['tags'].split(',').map(&:strip) + [@job.category.name, @job.localization.name, @job.company_name]
+ @tags = t('head.tags').split(',').map(&:strip) + [@job.category.name, @job.localization.name, @job.company_name]
@tags << JOB_TYPES[@job.type_id]
unless @job.framework.nil?
@tags << @job.framework.name
@page_title.insert(1, @job.framework.name)
end
unless @job.language.nil?
@page_title.insert(1, @job.language.name)
@tags << @job.language.name
end
set_meta_tags :keywords => @tags.join(', ')
respond_to do |format|
format.html # show.html.erb
end
end
# GET /jobs/new
# GET /jobs/new.xml
def new
@job = Job.new
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @job }
end
end
# POST /jobs
# POST /jobs.xml
def create
@job = Job.new(params[:job])
respond_to do |format|
if @job.save
flash[:notice] = t('flash.notice.email_verification')
format.html { redirect_to(@job) }
format.xml { render :xml => @job, :status => :created, :location => @job }
else
format.html { render :action => "new" }
format.xml { render :xml => @job.errors, :status => :unprocessable_entity }
end
end
end
# GET /jobs/1/edit
def edit
@job = Job.find_by_permalink_and_token!(params[:id], params[:token])
render :action => "new"
end
# PUT /jobs/1
# PUT /jobs/1.xml
def update
@job = Job.find_by_permalink_and_token!(params[:id], params[:token])
respond_to do |format|
if @job.update_attributes(params[:job])
flash[:notice] = t('flash.notice.job_updated')
format.html { redirect_to(@job) }
format.xml { head :ok }
else
format.html { render :action => "new" }
format.xml { render :xml => @job.errors, :status => :unprocessable_entity }
end
end
end
def publish
@job = Job.find_by_permalink_and_token!(params[:id], params[:token])
unless @job.published
@job.publish!
flash[:notice] = t('flash.notice.job_published')
end
redirect_to @job
end
# DELETE /jobs/1
# DELETE /jobs/1.xml
def destroy
@job = Job.find_by_permalink_and_token!(params[:id], params[:token])
@job.destroy
flash[:notice] = t('flash.notice.job_deleted')
respond_to do |format|
format.html { redirect_to(jobs_url) }
format.xml { head :ok }
end
end
end
diff --git a/app/models/job.rb b/app/models/job.rb
index 07b5989..c233e67 100644
--- a/app/models/job.rb
+++ b/app/models/job.rb
@@ -1,178 +1,178 @@
JOB_TYPES = ["freelance", "full_time", "free", "practice"]
JOB_ETAT = 1;
JOB_RANK_VALUES = {
:default => 0.3,
:price => 0.8,
:krs => 0.6,
:nip => 0.5,
:regon => 0.6,
:framework_id => 0.7,
:language_id => 0.7,
:website => 0.4,
:apply_online => 0.3
}
class Job < ActiveRecord::Base
include ActionController::UrlWriter
xss_terminate
has_permalink :title
named_scope :active, :conditions => ["((jobs.end_at >= ?) AND (jobs.published = ?))", Date.current, true]
named_scope :old, :conditions => ["jobs.end_at < ?", Date.current]
named_scope :has_text, lambda { |text| { :conditions => ["((jobs.title ILIKE ?) OR (jobs.description ILIKE ?))", "%#{text}%", "%#{text}%"] } }
validates_presence_of :title, :description, :email, :company_name, :localization_id, :category_id
validates_length_of :title, :within => 3..255
validates_length_of :description, :within => 10..5000
validates_inclusion_of :type_id, :in => 0..JOB_TYPES.size-1
validates_inclusion_of :availability_time, :in => 1..60
validates_numericality_of :price_from,
:greater_than => 0,
:unless => Proc.new { |j| j.price_from.nil? }
validates_numericality_of :price_to,
:greater_than => 0,
:unless => Proc.new { |j| j.price_to.nil? }
validates_format_of :email, :with => /([a-z0-9_.-]+)@([a-z0-9-]+)\.([a-z.]+)/i
validates_format_of :website, :with => /(^$)|(^(http|https):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(([0-9]{1,5})?\/.*)?$)/ix
validates_format_of :regon,
:with => /(^$)|(^[0-9]{7,14}$)/
validates_format_of :nip,
:with => /(^$)|(^\d{2,3}-\d{2,3}-\d{2,3}-\d{2,3}$)/
validates_format_of :krs,
:with => /(^$)|(^\d{10})$/
belongs_to :framework
belongs_to :localization
belongs_to :category
belongs_to :language
has_many :applicants, :dependent => :delete_all
has_many :visits, :dependent => :delete_all
attr_protected :rank, :permalink, :end_at, :token, :published
attr_accessor :framework_name, :localization_name
before_create :create_from_name, :generate_token
before_save :calculate_rank
after_create :send_notification
def self.find_grouped_by_type
return Job.active.count(:type_id, :group => "type_id")
end
def send_notification
JobMailer.deliver_job_posted(self)
end
def generate_token
alphanumerics = ('a'..'z').to_a.concat(('A'..'Z').to_a.concat(('0'..'9').to_a))
salt = alphanumerics.sort_by{rand}.to_s[0..1024]
self.token = Digest::SHA1.hexdigest("--#{salt}--#{self.id}--#{Date.current}--")
generate_token unless Job.find_by_token(self.token).nil?
end
def calculate_rank
self.rank = 1.0
self.rank += visits_count * 0.001 unless visits_count.nil?
self.rank += applicants_count * 0.01 unless applicants_count.nil?
[:regon, :nip, :krs, :framework_id, :website, :apply_online, :language_id].each do |attribute|
val = send(attribute)
inc = JOB_RANK_VALUES[attribute] || JOB_RANK_VALUES[:default]
self.rank += inc unless (val.nil? || (val.class == String && val.empty?) || (val.class == TrueClass))
end
if pay_band?
self.rank += JOB_RANK_VALUES[:price]
price = price_from || price_to
if price >= 10_000 # ciekawe czy ktoÅ da tyle :P
self.rank += 0.8
elsif price >= 7000
self.rank += 0.7
elsif price >= 5000
self.rank += 0.6
elsif price >= 3000
self.rank += 0.3
elsif price < 2000
if self.type_id == JOB_ETAT
self.rank -= 0.6 # bo nikt za grosze nie chce pracowaÄ
else
self.rank += 0.3 # chyba że to biedny student
end
end
end
end
def pay_band?
((!self.price_from.nil? && self.price_from > 0) || (!self.price_to.nil? && self.price_to > 0))
end
def create_from_name
unless (self.framework_name.nil? || self.framework_name.blank?)
framework = Framework.name_like(self.framework_name).first
framework = Framework.create(:name => self.framework_name) if framework.nil?
self.framework = framework
end
unless (self.localization_name.nil? || self.localization_name.blank?)
localization = Localization.name_like(self.localization_name).first
localization = Localization.create(:name => self.localization_name) if localization.nil?
self.localization = localization
end
end
def availability_time
date = created_at.nil? ? Date.current.to_date : created_at.to_date
return (read_attribute(:end_at) - date).to_i rescue 14
end
def availability_time=(val)
date = created_at.nil? ? Date.current.to_date : created_at.to_date
write_attribute(:end_at, date+val.to_i.days)
end
def highlighted?
self.rank >= 4.75
end
def publish!
self.published = true
save
spawn do
tags = [localization.name, category.name, "praca", JOB_TYPE[self.type_id]]
tags << framework.name unless framework.nil?
tags << language.name unless language.nil?
MicroFeed.send( :streams => :all,
- :msg => "[#{company_name}] - #{title}",
+ :msg => "#{title} dla #{company_name}",
:tags => tags,
:link => seo_job_url(self, :host => "webpraca.net")) if Rails.env == "production"
end
end
def visited_by(ip)
visit = visits.find_or_create_by_ip(IPAddr.new(ip).to_i)
visits_count += 1 if visit.new_record?
save
end
def to_param
permalink
end
end
diff --git a/app/views/layouts/admin.html.erb b/app/views/layouts/admin.html.erb
index 7f95d88..2dfbf77 100644
--- a/app/views/layouts/admin.html.erb
+++ b/app/views/layouts/admin.html.erb
@@ -1,49 +1,48 @@
<!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" lang="pl">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<%= display_meta_tags :site => WebSiteConfig['website']['name'] %>
<%= javascript_tag "window._token = '#{form_authenticity_token}'" %>
<%= javascript_include_merged :base %>
<%= javascript_include_merged :admin %>
<%= stylesheet_link_merged :base %>
</head>
<body>
<div class="wrapper">
<div class="header">
<h1 id="logo"><%= link_to "Panel administracyjny", admin_path %></h1>
<ul class="categories">
- <li><%= link_to "Statystyki", admin_stats_path, :class => params[:controller] == "admin/stats" ? "selected" : "normal" %></li>
- <li><%= link_to "Strony", admin_pages_path, :class => params[:controller] == "admin/pages" ? "selected" : "normal" %></li>
- <li><%= link_to "Kategorie", admin_categories_path, :class => params[:controller] == "admin/categories" ? "selected" : "normal" %></li>
- <li><%= link_to "Oferty", admin_jobs_path, :class => params[:controller] == "admin/jobs" ? "selected" : "normal" %></li>
- <li><%= link_to "Frameworki", admin_frameworks_path, :class => params[:controller] == "admin/frameworks" ? "selected" : "normal" %></li>
- <li><%= link_to "Ustawienia", admin_config_path, :class => params[:controller] == "admin/configs" ? "selected" : "normal" %></li>
+ <li><%= link_to "Stats", admin_stats_path, :class => params[:controller] == "admin/stats" ? "selected" : "normal" %></li>
+ <li><%= link_to "Pages", admin_pages_path, :class => params[:controller] == "admin/pages" ? "selected" : "normal" %></li>
+ <li><%= link_to "Categories", admin_categories_path, :class => params[:controller] == "admin/categories" ? "selected" : "normal" %></li>
+ <li><%= link_to "Jobs", admin_jobs_path, :class => params[:controller] == "admin/jobs" ? "selected" : "normal" %></li>
+ <li><%= link_to "Frameworks", admin_frameworks_path, :class => params[:controller] == "admin/frameworks" ? "selected" : "normal" %></li>
</ul>
<ul class="menu">
<li>Witaj <strong><%= self.current_user.email %></strong>!</li>
- <li><%= link_to "Wyloguj siÄ", logout_path %></li>
+ <li><%= link_to "Logout", logout_path %></li>
</ul>
</div>
<%- flash.each do |name, msg| -%>
<div class="<%= "flash #{name}" %>">
<a href="#" class="dismiss">X</a>
<p><%= msg %></p>
</div>
<%- end -%>
<div class="sidebar">
<%= yield :sidebar %>
</div>
<div class="content">
<%= yield %>
</div>
<div class="clear"></div>
</div>
<%= render :partial => "/shared/footer" %>
</body>
</html>
\ No newline at end of file
diff --git a/config/initializers/locales.rb b/config/initializers/locales.rb
new file mode 100644
index 0000000..9ecdf2a
--- /dev/null
+++ b/config/initializers/locales.rb
@@ -0,0 +1,16 @@
+module I18n
+ class << self
+ def available_locales; backend.available_locales; end
+ end
+ module Backend
+ class Simple
+ def available_locales; translations.keys.collect { |l| l.to_s }.sort; end
+ end
+ end
+end
+
+# You need to "force-initialize" loaded locales
+I18n.backend.send(:init_translations)
+
+AVAILABLE_LOCALES = I18n.backend.available_locales
+RAILS_DEFAULT_LOGGER.debug "* Loaded locales: #{AVAILABLE_LOCALES.inspect}"
\ No newline at end of file
diff --git a/config/locales/en.yml b/config/locales/en.yml
index 9f92c0e..e6d01ad 100644
--- a/config/locales/en.yml
+++ b/config/locales/en.yml
@@ -1,192 +1,193 @@
# Polish translations for Ruby on Rails
# by Jacek Becela (jacek.becela@gmail.com, http://github.com/ncr)
en:
+ head:
+ tags: "jobs, offers, IT, poland, developer, freelancer, job board, jobboard"
+ description: "Job board for ruby and rails developers. Subscribe to rss to keep up with new postings."
500:
- title: "CoÅ poszÅo nie tak... Aplikacja trafiÅa na nieobsÅugiwany wyjÄ
tek."
+ title: "We're sorry, but something went wrong"
404:
- title: "Nie znaleziono strony!"
+ title: "he page you were looking for doesn't exist"
applicant:
- title: "Aplikuj online"
- fieldset: "TreÅÄ aplikacji"
+ title: "Apply now"
+ fieldset: "Apply now"
contact:
- title: "Kontakt"
- description: "BÄdziemy wdziÄczni za wszelkie uwagi dotyczÄ
ce funkcjonowania serwisu."
- recipient: "Od"
- subject: "Temat"
- body: "TreÅÄ"
- submit: "WyÅlij!"
+ title: "Contact"
+ description: ""
+ recipient: "From"
+ subject: "Subject"
+ body: "Body"
+ submit: "Send!"
mailer:
job_applicant:
- body: "PojawiÅa siÄ osoba zainteresowana twojÄ
ofertÄ
: "
- attachment: "ZaÅÄ
cznik"
+ body: "Somebody just applied to your job opening: "
+ attachment: "Attachment"
job_posted:
- greetings: "Witaj"
- publish: "Aby opublikowaÄ swojÄ
ofertÄ kliknij na link poniżej"
- path_to_job: "Twoja oferta zostaÅa dodana i znajduje siÄ poda adresem:"
- path_to_edit_job: "Jeżeli chcesz wprowadziÄ zmiany w ofercie kliknij na link poniżej"
- path_to_destroy_job: "Aby usunÄ
Ä ofertÄ kliknij na poniższy link"
+ greetings: "Hello"
+ publish: "Click link below to publish your job"
+ path_to_job: "Your link to your job:"
+ path_to_edit_job: "If you want to edit job, click link below"
+ path_to_destroy_job: "If you want to remove job, click link below"
formtastic:
labels:
search:
- fieldset: "Wyszukiwarka"
- categories: "Kategorie"
- has_text: "ZawierajÄ
cy tekst"
- type: "Typ"
- localizations: "Lokalizacja"
- frameworks: "Używane frameworki"
- pay_band: "WideÅki zarobkowe"
- submit: "Szukaj!"
+ fieldset: "Search"
+ categories: "Category"
+ has_text: "Keywords"
+ type: "Type"
+ localizations: "Localization"
+ frameworks: "Framework"
+ pay_band: "Pay Band"
+ submit: "Search!"
websiteconfig:
groups:
website: "Strona WWW"
js: "Skrypty"
js:
google_analytics: "Google Analytics"
widget: "Reklama"
website:
name: "Nazwa"
tags: "SÅowa kluczowe"
description: "Opis"
applicant:
- email: "Twój E-Mail"
- body: "TreÅÄ"
- cv: "Dodaj ofertÄ/CV"
+ email: "Your E-Mail"
+ body: "Body"
+ cv: "Upload resume/CV"
job:
- title: "TytuÅ"
- place_id: "Lokalizacja"
- description: "Opis"
- availability_time: "DÅugoÅÄ trwania"
- remote_job: "Praca zdalna"
- type_id: "Typ"
- category_id: "Kategoria"
- company_name: "Nazwa"
- website: "Strona WWW"
+ title: "Title"
+ place_id: "Location"
+ description: "Descripion"
+ availability_time: "Availability time"
+ remote_job: "Remote job"
+ type_id: "Type"
+ category_id: "Category"
+ company_name: "Company"
+ website: "Website"
framework_name: "Framework"
- localization_id: "Lokalizacja"
- apply_online: "Aplikuj online"
- email_title: "TytuÅ emaila"
- language: "JÄzyk"
- pay_band: "WideÅki zarobkowe"
- pay_band_detail: "PLN na miesiÄ
c, netto"
- captcha: 'Kod z obrazka*'
+ localization_id: "Localization"
+ apply_online: "Apply online"
+ email_title: "Email title"
+ language: "Language"
+ pay_band: "Pay Band"
+ pay_band_detail: "$"
+ captcha: 'Captcha*'
user:
- password: "HasÅo"
- password_confirmation: "Powtórz hasÅo"
+ password: "password"
+ password_confirmation: "Password Confirmation"
hints:
applicant:
- body: "wiadomoÅÄ lub list motywacyjny"
- cv: "Max. 5 MB. Rekomendowane formaty: PDF, DOC, TXT, RTF, ZIP, RAR."
+ body: "Message or letter of intention"
+ cv: "Max. 5 MB. Recommended formats: PDF, DOC, TXT, RTF, ZIP, RAR."
job:
- availability_time: "ile dni oferta ma byÄ ważna(od 1 do 60 dni)"
- localization_id: "np. 'Warszawa', 'Kraków, UK'"
- framework_id: "gÅówny framework którego znajomoÅÄ jest wymagana, podaj peÅnÄ
nazwÄ"
- apply_online: "uaktywnia formularz umożliwiajÄ
cy przesyÅanie aplikacji online w ofercie"
- email_title: "np. MÅodszy programista, Ruby Developer/18/12/71 itp"
- email: "Pod wskazany adres zostanÄ
przesÅane linki do edycji oferty, nie bÄdzie on widoczny publicznie(zamiast niego bÄdzie dostÄpny formularz kontaktowy)."
+ availability_time: "from 1 to 60 days"
+ localization_id: "ex. 'London', 'Berlin, UK'"
+ email_title: "ex. Senior Developer, Ruby Developer/18/12/71"
website: "http://"
+ framework_id: "ex. Ruby On Rails, Sinatra"
flash:
error:
access_denied: "Access denied"
notice:
email_verification: "On your email was verification email!"
job_updated: "Your job was successfully updated!"
job_published: "Your job was successfully published!"
job_deleted: "Job was deleted!"
contact_sended: "Thank you!"
application_sended: "Your application was sended!"
title:
popular: "popular jobs"
latest: "latest jobs"
search: "Search Job"
finded_jobs: "Finded Jobs"
jobs: "Jobs"
admin: "Admin panel"
jobs:
empty: "Empty"
show:
type: "Type"
category: "Category"
rank: "Rank"
employer: "Employer"
localization: "Localization"
framework: "Framework"
language: "Language"
pay_band: "Pay Band"
contact: "Contact"
published_at: "Posted"
end_at: "End at"
visited: "Visited"
description: "Description"
apply_online: "Apply online!"
form:
new:
title: "Post Job"
submit: "I agree with Terms and I want post job"
cancel: "cancel"
edit:
title: "Edit job"
submit: "Save changes"
destroy: "delete"
destroy_confirm: "Are you sure?"
fieldset:
job_details: "Details"
apply_online: "Apply on-line!"
company_details: "Company info"
human_test: "Are you human?"
type:
full_time: "Full-Time"
freelance: "freelance"
free: "free"
practice: "practice"
remote: "remote"
type_long:
full_time: "Full time job"
freelance: "freelance"
free: "free"
practice: "practice"
layout:
popular: "Popular"
latest: "Latest"
menu:
main: "Home"
search: "Search"
about: "About"
terms: "Terms"
follow: "Follow us"
contact: "Contact"
sidebar:
post_job: "Post Job for FREE!"
type: "type"
localization: "localization"
language: "language"
frameworks: "framework"
home:
title: "latest jobs from IT"
popular: "Popular"
latest: "Latest"
jobs: "jobs"
more_jobs: "show more"
datetime:
distance_in_words:
ago: "ago"
activerecord:
models:
user: "User"
job: "Job"
search: "Search"
applicant: "Applicant"
comment:
attributes:
captcha_solution:
blank: 'must be presented'
invalid: 'invalid input'
support:
array:
last_word_connector: " and "
for_word_connector: " for "
in_word_connector: " in "
or_word_connector: " or "
diff --git a/config/locales/pl.yml b/config/locales/pl.yml
index d6dac4b..a9fb975 100644
--- a/config/locales/pl.yml
+++ b/config/locales/pl.yml
@@ -1,312 +1,315 @@
# Polish translations for Ruby on Rails
# by Jacek Becela (jacek.becela@gmail.com, http://github.com/ncr)
pl:
+ head:
+ tags: "oferty pracy, praca IT, zlecenia IT, praca w IT, praca oferty z IT, oferty z it, it, w IT"
+ description: "Oferty pracy oraz zlece\xC5\x84 w bran\xC5\xBCy IT. Skutecznie rekrutuj z nami pracownik\xC3\xB3w, freelancer\xC3\xB3w."
500:
title: "CoÅ poszÅo nie tak... Aplikacja trafiÅa na nieobsÅugiwany wyjÄ
tek."
404:
title: "Nie znaleziono strony!"
applicant:
title: "Aplikuj online"
fieldset: "TreÅÄ aplikacji"
contact:
title: "Kontakt"
description: "BÄdziemy wdziÄczni za wszelkie uwagi dotyczÄ
ce funkcjonowania serwisu."
recipient: "Od"
subject: "Temat"
body: "TreÅÄ"
submit: "WyÅlij!"
mailer:
job_applicant:
body: "PojawiÅa siÄ osoba zainteresowana twojÄ
ofertÄ
: "
attachment: "ZaÅÄ
cznik"
job_posted:
greetings: "Witaj"
publish: "Aby opublikowaÄ swojÄ
ofertÄ kliknij na link poniżej"
path_to_job: "Twoja oferta zostaÅa dodana i znajduje siÄ poda adresem:"
path_to_edit_job: "Jeżeli chcesz wprowadziÄ zmiany w ofercie kliknij na link poniżej"
path_to_destroy_job: "Aby usunÄ
Ä ofertÄ kliknij na poniższy link"
formtastic:
labels:
search:
fieldset: "Wyszukiwarka"
categories: "Kategorie"
has_text: "ZawierajÄ
cy tekst"
type: "Typ"
localizations: "Lokalizacja"
frameworks: "Używane frameworki"
pay_band: "WideÅki zarobkowe"
submit: "Szukaj!"
websiteconfig:
groups:
website: "Strona WWW"
js: "Skrypty"
js:
google_analytics: "Google Analytics"
widget: "Reklama"
website:
name: "Nazwa"
tags: "SÅowa kluczowe"
description: "Opis"
applicant:
email: "Twój E-Mail"
body: "TreÅÄ"
cv: "Dodaj ofertÄ/CV"
job:
title: "TytuÅ"
place_id: "Lokalizacja"
description: "Opis"
availability_time: "DÅugoÅÄ trwania"
remote_job: "Praca zdalna"
type_id: "Typ"
category_id: "Kategoria"
company_name: "Nazwa"
website: "Strona WWW"
framework_name: "Framework"
localization_id: "Lokalizacja"
apply_online: "Aplikuj online"
email_title: "TytuÅ emaila"
language: "JÄzyk"
pay_band: "WideÅki zarobkowe"
pay_band_detail: "PLN na miesiÄ
c, netto"
captcha: 'Kod z obrazka*'
user:
password: "HasÅo"
password_confirmation: "Powtórz hasÅo"
hints:
applicant:
body: "wiadomoÅÄ lub list motywacyjny"
cv: "Max. 5 MB. Rekomendowane formaty: PDF, DOC, TXT, RTF, ZIP, RAR."
job:
availability_time: "ile dni oferta ma byÄ ważna(od 1 do 60 dni)"
localization_id: "np. 'Warszawa', 'Kraków, UK'"
framework_id: "gÅówny framework którego znajomoÅÄ jest wymagana, podaj peÅnÄ
nazwÄ"
apply_online: "uaktywnia formularz umożliwiajÄ
cy przesyÅanie aplikacji online w ofercie"
email_title: "np. MÅodszy programista, Ruby Developer/18/12/71 itp"
email: "Pod wskazany adres zostanÄ
przesÅane linki do edycji oferty, nie bÄdzie on widoczny publicznie(zamiast niego bÄdzie dostÄpny formularz kontaktowy)."
website: "zaczynajÄ
cy siÄ od http://"
flash:
error:
access_denied: "Nie masz wystarczajÄ
cych uprawnieÅ aby móc odwiedziÄ tÄ
stronÄ"
notice:
email_verification: "Na twój e-mail zostaÅ wysÅany link którym opublikujesz ofertÄ."
job_updated: "Zapisano zmiany w ofercie."
job_published: "Twoja oferta jest już widoczna!"
job_deleted: "Oferta zostaÅa usuniÄta"
contact_sended: "DziÄkujemy za wiadomoÅÄ!"
application_sended: "Twoja aplikacja zostaÅa wysÅana"
title:
popular: "najpopularniejsze oferty pracy IT"
latest: "najnowsze oferty pracy IT"
search: "Szukaj oferty"
finded_jobs: "Znalezione oferty"
jobs: "Oferty pracy IT"
admin: "Panel administracyjny"
jobs:
empty: "Brak ofert"
show:
type: "Typ"
category: "Kategoria"
rank: "Ocena"
employer: "Pracodawca"
localization: "Lokalizacje"
framework: "Framework"
language: "JÄzyk"
pay_band: "WideÅko zarobkowe"
contact: "Kontakt"
published_at: "Data rozpoczÄcia"
end_at: "Data zakoÅczenia"
visited: "WyÅwietlona"
description: "Opis oferty"
apply_online: "Aplikuj online!"
form:
new:
title: "Nowa oferta"
submit: "Zgadzam siÄ z regulaminem i chcÄ dodaÄ ofertÄ"
cancel: "anuluj"
edit:
title: "Edytuj ofertÄ"
submit: "Zapisz zmiany"
destroy: "usuÅ"
destroy_confirm: "Czy na pewno chcesz usunÄ
Ä ofertÄ?"
fieldset:
job_details: "SzczegóÅy oferty pracy"
apply_online: "Aplikuj online"
company_details: "Firma zatrudniajÄ
ca lub osoba zlecajÄ
ca"
human_test: "Czy jesteÅ czÅowiekiem"
type:
full_time: "etat"
freelance: "zlecenie"
free: "wolontariat"
practice: "praktyka"
remote: "praca zdalna"
type_long:
full_time: "poszukiwanie wspóÅpracowników / oferta pracy"
freelance: "zlecenie (konkretna usÅuga do wykonania)"
free: "wolontariat (praca za reklamy, bannery, itp. lub praca za darmo)"
practice: "staż/praktyka"
layout:
popular: "Najpopularniejsze"
latest: "Najnowsze"
menu:
main: "Strona gÅówna"
search: "Szukaj"
about: "O serwisie"
terms: "Regulamin"
follow: "Obserwuj nas"
contact: "Kontakt"
sidebar:
post_job: "Dodaj ofertÄ za DARMO!"
type: "typ"
localization: "lokalizacje"
language: "jÄzyk"
frameworks: "framework"
home:
title: "najpopularniejsze i najnowsze oferty pracy z IT"
popular: "Najpopularniejsze"
latest: "Najnowsze"
jobs: "oferty"
more_jobs: "pokaż wiÄcej ofert"
number:
format:
separator: ","
delimiter: " "
precision: 2
currency:
format:
format: "%n %u"
unit: "PLN"
percentage:
format:
delimiter: ""
precision:
format:
delimiter: ""
human:
format:
delimiter: ""
precision: 1
storage_units:
format: "%n %u"
units:
byte:
one: "bajt"
other: "bajty"
kb: "KB"
mb: "MB"
gb: "GB"
tb: "TB"
date:
formats:
default: "%Y-%m-%d"
short: "%d %b"
school: "%Y"
simple: "%d.%m.%Y"
long: "%d %B %Y"
day_names: [Niedziela, PoniedziaÅek, Wtorek, Åroda, Czwartek, PiÄ
tek, Sobota]
abbr_day_names: [nie, pon, wto, Åro, czw, pia, sob]
month_names: [~, StyczeÅ, Luty, Marzec, KwiecieÅ, Maj, Czerwiec, Lipiec, SierpieÅ, WrzesieÅ, Październik, Listopad, GrudzieÅ]
abbr_month_names: [~, sty, lut, mar, kwi, maj, cze, lip, sie, wrz, paź, lis, gru]
order: [ :year, :month, :day ]
time:
formats:
default: "%a, %d %b %Y, %H:%M:%S %z"
short: "%d %b, %H:%M"
long: "%d %B %Y, %H:%M"
am: "przed poÅudniem"
pm: "po poÅudniu"
datetime:
distance_in_words:
ago: "temu"
half_a_minute: "póŠminuty"
less_than_x_seconds:
one: "mniej niż sekundÄ"
few: "mniej niż {{count}} sekundy"
other: "mniej niż {{count}} sekund"
x_seconds:
one: "sekundÄ"
few: "{{count}} sekundy"
other: "{{count}} sekund"
less_than_x_minutes:
one: "mniej niż minutÄ"
few: "mniej niż {{count}} minuty"
other: "mniej niż {{count}} minut"
x_minutes:
one: "minutÄ"
few: "{{count}} minuty"
other: "{{count}} minut"
about_x_hours:
one: "okoÅo godziny"
other: "okoÅo {{count}} godzin"
x_days:
one: "1 dzieÅ"
other: "{{count}} dni"
about_x_months:
one: "okoÅo miesiÄ
ca"
other: "okoÅo {{count}} miesiÄcy"
x_months:
one: "1 miesiÄ
c"
few: "{{count}} miesiÄ
ce"
other: "{{count}} miesiÄcy"
about_x_years:
one: "okoÅo roku"
other: "okoÅo {{count}} lat"
over_x_years:
one: "ponad rok"
few: "ponad {{count}} lata"
other: "ponad {{count}} lat"
activerecord:
models:
user: "Użytkownik"
job: "Praca"
search: "Wyszukiwarka"
applicant: "Aplikant"
comment:
attributes:
captcha_solution:
blank: 'musi byÄ podane'
invalid: 'odpowiedź jest niepoprawna'
errors:
template:
header:
one: "{{model}} nie zostaÅ zachowany z powodu jednego bÅÄdu"
other: "{{model}} nie zostaÅ zachowany z powodu {{count}} bÅÄdów"
body: "BÅÄdy dotyczÄ
nastÄpujÄ
cych pól:"
messages:
inclusion: "nie znajduje siÄ na liÅcie dopuszczalnych wartoÅci"
exclusion: "znajduje siÄ na liÅcie zabronionych wartoÅci"
invalid: "jest nieprawidÅowe"
confirmation: "nie zgadza siÄ z potwierdzeniem"
accepted: "musi byÄ zaakceptowane"
empty: "nie może byÄ puste"
blank: "nie może byÄ puste"
too_long: "jest za dÅugie (maksymalnie {{count}} znaków)"
too_short: "jest za krótkie (minimalnie {{count}} znaków)"
wrong_length: "jest nieprawidÅowej dÅugoÅci (powinna wynosiÄ {{count}} znaków)"
taken: "zostaÅo już zajÄte"
not_a_number: "nie jest liczbÄ
"
greater_than: "musi byÄ wiÄksze niż {{count}}"
greater_than_or_equal_to: "musi byÄ wiÄksze lub równe {{count}}"
equal_to: "musi byÄ równe {{count}}"
less_than: "musi byÄ mniejsze niż {{count}}"
less_than_or_equal_to: "musi byÄ mniejsze lub równe {{count}}"
odd: "musi byÄ nieparzyste"
even: "musi byÄ parzyste"
record_invalid: "nieprawidÅowe dane"
support:
array:
sentence_connector: "i"
skip_last_comma: true
words_connector: ", "
two_words_connector: " i "
last_word_connector: " oraz "
for_word_connector: " dla "
in_word_connector: " w "
or_word_connector: " albo "
diff --git a/config/routes.rb b/config/routes.rb
index e7634ad..431698c 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -1,90 +1,89 @@
ActionController::Routing::Routes.draw do |map|
map.new_contact '/contact/new', :controller => 'contact', :action => 'new', :conditions => { :method => :get }
map.contact '/contact', :controller => 'contact', :action => 'new', :conditions => { :method => :get }
map.contact '/contact', :controller => 'contact', :action => 'create', :conditions => { :method => :post }
map.seo_page '/page/:id/', :controller => 'admin/pages', :action => 'show'
map.with_options :controller => 'jobs', :action => 'index' do |job|
job.with_options :category => nil, :page => 1, :order => "latest", :requirements => { :order => /(latest|popular)/, :page => /\d/ } do |seo|
seo.connect '/jobs/:page'
seo.connect '/jobs/:order'
seo.connect '/jobs/:order/:page'
seo.seo_jobs '/jobs/:order/:category/:page'
end
job.connect '/localization/:localization/:page'
job.localization '/localization/:localization'
job.connect '/framework/:framework/:page'
job.framework '/framework/:framework'
job.connect '/language/:language/:page'
job.language '/language/:language'
job.connect '/type/:type_id/:page'
job.job_type '/type/:type_id'
job.connect '/category/:category/:page'
job.job_category '/category/:category'
end
map.resources :jobs, :member => { :publish => :get, :destroy => :any }, :collection => { :search => :any, :widget => :get } do |jobs|
jobs.resources :applicants, :member => { :download => :get }
end
map.resource :widget
map.resources :user_sessions
map.login '/login', :controller => 'user_sessions', :action => 'new'
map.logout '/logout', :controller => 'user_sessions', :action => 'destroy'
map.namespace :admin do |admin|
admin.stats '/stats', :controller => "stats"
- admin.config '/config', :controller => "configs", :action => "new"
admin.resources :pages
admin.resources :jobs
admin.resource :configs
admin.resources :frameworks
admin.resources :categories, :collection => { :reorder => :post }
end
map.admin '/admin', :controller => "admin/stats"
# The priority is based upon order of creation: first created -> highest priority.
# Sample of regular route:
# map.connect 'products/:id', :controller => 'catalog', :action => 'view'
# Keep in mind you can assign values other than :controller and :action
# Sample of named route:
# map.purchase 'products/:id/purchase', :controller => 'catalog', :action => 'purchase'
# This route can be invoked with purchase_url(:id => product.id)
# Sample resource route (maps HTTP verbs to controller actions automatically):
# map.resources :products
# Sample resource route with options:
# map.resources :products, :member => { :short => :get, :toggle => :post }, :collection => { :sold => :get }
# Sample resource route with sub-resources:
# map.resources :products, :has_many => [ :comments, :sales ], :has_one => :seller
# Sample resource route with more complex sub-resources
# map.resources :products do |products|
# products.resources :comments
# products.resources :sales, :collection => { :recent => :get }
# end
# Sample resource route within a namespace:
# map.namespace :admin do |admin|
# # Directs /admin/products/* to Admin::ProductsController (app/controllers/admin/products_controller.rb)
# admin.resources :products
# end
map.root :controller => "jobs", :action => "home"
map.seo_job '/:id', :controller => 'jobs', :action => 'show'
# You can have the root of your site routed with map.root -- just remember to delete public/index.html.
# See how all your routes lay out with "rake routes"
# Install the default routes as the lowest priority.
# Note: These default routes make all actions in every controller accessible via GET requests. You should
# consider removing or commenting them out if you're using named routes and resources.
map.connect ':controller/:action/:id'
map.connect ':controller/:action/:id.:format'
end
diff --git a/config/sitemap.rb b/config/sitemap.rb
index 69522d0..b004e3c 100644
--- a/config/sitemap.rb
+++ b/config/sitemap.rb
@@ -1,61 +1,62 @@
# Set the host name for URL creation
SitemapGenerator::Sitemap.default_host = "http://webpraca.net"
SitemapGenerator::Sitemap.add_links do |sitemap|
# Put links creation logic here.
#
# The root path '/' and sitemap index file are added automatically.
# Links are added to the Sitemap in the order they are specified.
#
# Usage: sitemap.add path, options
# (default options are used if you don't specify)
#
# Defaults: :priority => 0.5, :changefreq => 'weekly',
# :lastmod => Time.now, :host => default_host
# Examples:
-
- # add '/articles'
- sitemap.add jobs_path, :priority => 1.0, :changefreq => 'daily'
- # add all individual articles
- Job.active.each do |o|
- sitemap.add seo_job_path(o), :lastmod => o.updated_at
+ AVAILABLE_LOCALES.each do |lang|
+ sitemap.add jobs_path(:locale => lang), :priority => 1.0, :changefreq => 'daily'
+ # add all individual articles
+ Job.active.each do |o|
+ sitemap.add seo_job_path(o,:locale => lang), :lastmod => o.updated_at
+ end
+
+ Framework.all.each do |f|
+ latest_job = f.jobs.first(:order => "created_at DESC")
+ sitemap.add framework_path(f,:locale => lang), :lastmod => latest_job.nil? ? f.created_at : latest_job.created_at
+ end
+
+ Localization.all.each do |l|
+ latest_job = l.jobs.first(:order => "created_at DESC")
+ sitemap.add localization_path(l,:locale => lang), :lastmod => latest_job.nil? ? l.created_at : latest_job.created_at
+ end
+
+ Category.all.each do |c|
+ latest_job = c.jobs.first(:order => "created_at DESC")
+ sitemap.add job_category_path(c,:locale => lang), :lastmod => latest_job.nil? ? c.created_at : latest_job.created_at
+ end
+
+ Language.all.each do |l|
+ latest_job = l.jobs.first(:order => "created_at DESC")
+ sitemap.add language_path(l,:locale => lang), :lastmod => latest_job.nil? ? l.created_at : latest_job.created_at
+ end
+
+ Page.all.each do |page|
+ sitemap.add seo_page_path(page,:locale => lang), :lastmod => page.updated_at
+ end
end
-
- Framework.all.each do |f|
- latest_job = f.jobs.first(:order => "created_at DESC")
- sitemap.add framework_path(f), :lastmod => latest_job.nil? ? f.created_at : latest_job.created_at
- end
-
- Localization.all.each do |l|
- latest_job = l.jobs.first(:order => "created_at DESC")
- sitemap.add localization_path(l), :lastmod => latest_job.nil? ? l.created_at : latest_job.created_at
- end
-
- Category.all.each do |c|
- latest_job = c.jobs.first(:order => "created_at DESC")
- sitemap.add job_category_path(c), :lastmod => latest_job.nil? ? c.created_at : latest_job.created_at
- end
-
- Language.all.each do |l|
- latest_job = l.jobs.first(:order => "created_at DESC")
- sitemap.add language_path(l), :lastmod => latest_job.nil? ? l.created_at : latest_job.created_at
- end
-
- Page.all.each do |page|
- sitemap.add seo_page_path(page), :lastmod => page.updated_at
- end
+
end
# Including Sitemaps from Rails Engines.
#
# These Sitemaps should be almost identical to a regular Sitemap file except
# they needn't define their own SitemapGenerator::Sitemap.default_host since
# they will undoubtedly share the host name of the application they belong to.
#
# As an example, say we have a Rails Engine in vendor/plugins/cadability_client
# We can include its Sitemap here as follows:
#
# file = File.join(Rails.root, 'vendor/plugins/cadability_client/config/sitemap.rb')
# eval(open(file).read, binding, file)
\ No newline at end of file
diff --git a/config/website_config.yml.example b/config/website_config.yml.example
index d485f96..1633215 100644
--- a/config/website_config.yml.example
+++ b/config/website_config.yml.example
@@ -1,5 +1,6 @@
website:
name: My website
- tags: [ cool, website ]
- author: Buras Arkadiusz
- last_update: <%= Time.now %>
+ default_language: en
+js:
+ google_analytics: ""
+ widget: ""
diff --git a/vendor/plugins/subdomain-fu/CHANGELOG b/vendor/plugins/subdomain-fu/CHANGELOG
new file mode 100644
index 0000000..3696fd1
--- /dev/null
+++ b/vendor/plugins/subdomain-fu/CHANGELOG
@@ -0,0 +1,20 @@
+== 2009-09-13
+
+* Added current_domain method
+* Added controller & view usage to readme
+* Added more tests
+* Fixing load paths
+
+== 2009-08-26
+
+* Fixed needs_rewrite? method
+* Added is_mirror? method
+* Added tests, and fixed failing tests
+
+== 2009-08-24
+
+* Merged forks that added lots of features, tests, and fixes
+
+== 2008-06-25
+
+* Removed stray puts
diff --git a/vendor/plugins/subdomain-fu/MIT-LICENSE b/vendor/plugins/subdomain-fu/MIT-LICENSE
new file mode 100644
index 0000000..bfee431
--- /dev/null
+++ b/vendor/plugins/subdomain-fu/MIT-LICENSE
@@ -0,0 +1,21 @@
+Copyright (c) 2008 Michael Bleigh (http://www.mbleigh.com) and
+ Intridea, Inc (http://www.intridea.com)
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+"Software"), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/vendor/plugins/subdomain-fu/README.rdoc b/vendor/plugins/subdomain-fu/README.rdoc
new file mode 100644
index 0000000..81891b7
--- /dev/null
+++ b/vendor/plugins/subdomain-fu/README.rdoc
@@ -0,0 +1,110 @@
+= SubdomainFu
+
+SubdomainFu provides a modern implementation of subdomain handling in Rails.
+It takes aspects from account_location, request_routing, and other snippets
+found around the web and combines them to provide a single, simple solution
+for subdomain-based route and url management.
+
+== Installation
+
+SubdomainFu is available both as a traditional plugin and a GemPlugin. To
+install it as a traditional plugin (Rails 2.1 or later):
+
+ script/plugin install git://github.com/mbleigh/subdomain-fu.git
+
+To use it as a gem, add it to your config/environment.rb:
+
+ config.gem 'subdomain-fu'
+
+
+== Examples
+
+SubdomainFu works inside of Rails's URL Writing mechanisms to provide an easy and seamless
+way to link and otherwise understand cross-subdomain routing. You can use the :subdomain
+option both in named and non-named routes as well as in generated resources routes.
+
+Let's say my domain is 'intridea.com'. Here are some examples of the use of the :subdomain
+option:
+
+ url_for(:controller => "my_controller",
+ :action => "my_action",
+ :subdomain => "awesome") # => http://awesome.intridea.com/my_controller/my_action
+
+Now let's say I'm at http://awesome.intridea.com/ and I want back to the root.
+Specifying "false" will remove any current subdomain:
+
+ users_url(:subdomain => false) # => http://intridea.com/users
+
+Note that this plugin does not honor the :only_path notion of routing when doing
+so would go against the intent of the command. For example, if I were at http://intridea.com
+again:
+
+ users_path(:subdomain => "fun") # => http://fun.intridea.com/users
+ users_path(:subdomain => false) # => /users
+
+In this way you can rest assured that you will never misdirect your links to the
+same subdomain when you meant to change it.
+
+== Use in controllers and views
+
+You have access to current_subdomain and current_domain methods.
+
+[current_subdomain] returns all subdomains. For the URL http://awesome.website.stuff.example.com, it will return "awesome.website.stuff"
+
+[current_domain] returns all subdomains except for the subdomain, including the TLD. For the URL http://awesome.website.stuff.example.com, it will return "website.stuff.example.com"
+
+If what you really want is the entire domain, then use <tt>request.domain</tt> in
+your controllers. The purpose of current_domain is to only strip off the first
+subdomain, if any, and return what's left.
+
+== Configuration
+
+You may need to configure SubdomainFu based on your development setup. The
+configuration required is:
+
+=== TLD Size
+
+A hash for each environment of the size of the top-level domain name.
+(something.com = 1, localhost = 0, etc.)
+
+ SubdomainFu.tld_size = 1 # sets for current environment
+ SubdomainFu.tld_sizes = {:development => 0,
+ :test => 0,
+ :production => 1} # set all at once (also the defaults)
+
+=== Mirrors
+
+Mirrors are the subdomains that are equivalent to no subdomain (i.e. they 'mirror')
+the usage of the root domain.
+
+ SubdomainFu.mirrors = %w(www site we) # Defaults to %w(www)
+
+=== Preferred Mirror
+
+SubdomainFu also understands the notion of a 'preferred mirror', that is, if you
+always want your links going to 'www.yourdomain.com' instead of 'yourdomain.com',
+you can set the preferred mirror like so:
+
+ SubdomainFu.preferred_mirror = "www"
+
+Now when you create a link with <tt>:subdomain => false</tt> in the options the subdomain
+will default to the preferred mirror.
+
+== Routing
+
+SubdomainFu can also work within Rails' routing for subdomain-specific routes. For instance, if you only wanted your administrative tools available in the "admin" subdomain you could add this to your <tt>config/routes.rb</tt> file:
+
+ map.with_options :conditions => {:subdomain => 'admin'} do |admin|
+ admin.resources :posts
+ admin.resources :users
+ end
+
+In addition to specifying a string, you could also specify <tt>false</tt> to require no subdomain (this includes mirrors that you've set up such as www) or a regular expression to match a range of subdomains.
+
+== Resources
+
+* GitHub Repository: http://github.com/mbleigh/subdomain-fu
+* RDocs: http://rdoc.info/projects/mbleigh/subdomain-fu
+
+Copyright (c) 2008 Michael Bleigh (http://www.mbleigh.com/) and
+Intridea, Inc. (http://www.intridea.com/). Released under the MIT license
diff --git a/vendor/plugins/subdomain-fu/Rakefile b/vendor/plugins/subdomain-fu/Rakefile
new file mode 100644
index 0000000..bea8b0f
--- /dev/null
+++ b/vendor/plugins/subdomain-fu/Rakefile
@@ -0,0 +1,56 @@
+require 'rake'
+require 'spec/rake/spectask'
+
+desc 'Default: run specs.'
+task :default => :spec
+
+desc 'Run the specs'
+Spec::Rake::SpecTask.new(:spec) do |t|
+ t.spec_opts = ['--colour --format progress --loadby mtime --reverse']
+ t.spec_files = FileList['spec/**/*_spec.rb']
+end
+
+begin
+ require 'jeweler'
+ Jeweler::Tasks.new do |gemspec|
+ gemspec.name = "subdomain-fu"
+ gemspec.rubyforge_project = 'subdomain-fu'
+ gemspec.summary = "SubdomainFu is a Rails plugin that provides subdomain routing and URL writing helpers."
+ gemspec.email = "michael@intridea.com"
+ gemspec.homepage = "http://github.com/mbleigh/subdomain-fu"
+ gemspec.files = FileList["[A-Z]*", "{lib,spec,rails}/**/*"] - FileList["**/*.log"]
+ gemspec.description = "SubdomainFu is a Rails plugin to provide all of the basic functionality necessary to handle multiple subdomain applications (such as Basecamp-esque subdomain accounts and more)."
+ gemspec.authors = ["Michael Bleigh"]
+ end
+ Jeweler::GemcutterTasks.new
+rescue LoadError
+ puts "Jeweler not available. Install it with: sudo gem install technicalpickles-jeweler -s http://gems.github.com"
+end
+
+
+# These are new tasks
+begin
+ require 'rake/contrib/sshpublisher'
+ namespace :rubyforge do
+
+ desc "Release gem and RDoc documentation to RubyForge"
+ task :release => ["rubyforge:release:gem", "rubyforge:release:docs"]
+
+ namespace :release do
+ desc "Publish RDoc to RubyForge."
+ task :docs => [:rdoc] do
+ config = YAML.load(
+ File.read(File.expand_path('~/.rubyforge/user-config.yml'))
+ )
+
+ host = "#{config['username']}@rubyforge.org"
+ remote_dir = "/var/www/gforge-projects/the-perfect-gem/"
+ local_dir = 'rdoc'
+
+ Rake::SshDirPublisher.new(host, remote_dir, local_dir).upload
+ end
+ end
+ end
+rescue LoadError
+ puts "Rake SshDirPublisher is unavailable or your rubyforge environment is not configured."
+end
\ No newline at end of file
diff --git a/vendor/plugins/subdomain-fu/VERSION.yml b/vendor/plugins/subdomain-fu/VERSION.yml
new file mode 100644
index 0000000..535df8e
--- /dev/null
+++ b/vendor/plugins/subdomain-fu/VERSION.yml
@@ -0,0 +1,5 @@
+---
+:major: 0
+:build:
+:minor: 5
+:patch: 4
diff --git a/vendor/plugins/subdomain-fu/init.rb b/vendor/plugins/subdomain-fu/init.rb
new file mode 100644
index 0000000..9025822
--- /dev/null
+++ b/vendor/plugins/subdomain-fu/init.rb
@@ -0,0 +1 @@
+require "rails/init"
diff --git a/vendor/plugins/subdomain-fu/install.sh b/vendor/plugins/subdomain-fu/install.sh
new file mode 100644
index 0000000..8f28e1d
--- /dev/null
+++ b/vendor/plugins/subdomain-fu/install.sh
@@ -0,0 +1,2 @@
+# I use this to make life easier when installing and testing from source:
+rm -rf subdomain-fu-*.gem && gem build subdomain-fu.gemspec && sudo gem uninstall subdomain-fu && sudo gem install subdomain-fu-0.5.2.gem --no-ri --no-rdoc
diff --git a/vendor/plugins/subdomain-fu/lib/subdomain-fu.rb b/vendor/plugins/subdomain-fu/lib/subdomain-fu.rb
new file mode 100644
index 0000000..7b4a9da
--- /dev/null
+++ b/vendor/plugins/subdomain-fu/lib/subdomain-fu.rb
@@ -0,0 +1,161 @@
+require 'subdomain_fu/routing_extensions'
+require 'subdomain_fu/url_rewriter'
+
+module SubdomainFu
+ # The length of the period-split top-level domain for each environment.
+ # For example, "localhost" has a tld_size of zero, and "something.co.uk"
+ # has a tld_size of two.
+ #
+ # To set a tld size for a given environment, just call SubdomainFu.tld_sizes[:environment] = value
+ DEFAULT_TLD_SIZES = {:development => 0, :test => 0, :production => 1}
+ mattr_accessor :tld_sizes
+ @@tld_sizes = DEFAULT_TLD_SIZES.dup
+
+ # Subdomains that are equivalent to going to the website with no subdomain at all.
+ # Defaults to "www" as the only member.
+ DEFAULT_MIRRORS = %w(www)
+ mattr_accessor :mirrors
+ @@mirrors = DEFAULT_MIRRORS.dup
+
+ mattr_accessor :preferred_mirror
+ @@preferred_mirror = nil
+
+ mattr_accessor :override_only_path
+ @@override_only_path = false
+
+ # Returns the TLD Size of the current environment.
+ def self.tld_size
+ tld_sizes[RAILS_ENV.to_sym]
+ end
+
+ # Sets the TLD Size of the current environment
+ def self.tld_size=(value)
+ tld_sizes[RAILS_ENV.to_sym] = value
+ end
+
+ # Is the current subdomain either nil or not a mirror?
+ def self.has_subdomain?(subdomain)
+ subdomain != false && !subdomain.blank? && !SubdomainFu.mirrors.include?(subdomain)
+ end
+
+ def self.is_mirror?(subdomain)
+ subdomain != false && !subdomain.blank? && SubdomainFu.mirrors.include?(subdomain)
+ end
+
+ # Is the subdomain a preferred mirror
+ def self.preferred_mirror?(subdomain)
+ subdomain == SubdomainFu.preferred_mirror || SubdomainFu.preferred_mirror.nil?
+ end
+
+ # Gets the subdomain from the host based on the TLD size
+ def self.subdomain_from(host)
+ return nil if host.nil? || /\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.match(host)
+ parts = host.split('.')
+ sub = parts[0..-(SubdomainFu.tld_size+2)].join(".")
+ sub.blank? ? nil : sub
+ end
+
+ # Gets only non-mirror subdomains from the host based on the TLD size
+ def self.non_mirror_subdomain_from(host)
+ sub = subdomain_from(host)
+ has_subdomain?(sub) ? sub : nil
+ end
+
+ def self.host_without_subdomain(host)
+ parts = host.split('.')
+ parts[-(SubdomainFu.tld_size+1)..-1].join(".")
+ end
+
+ # Rewrites the subdomain of the host unless they are equivalent (i.e. mirrors of each other)
+ def self.rewrite_host_for_subdomains(subdomain, host)
+ if needs_rewrite?(subdomain, host)
+ change_subdomain_of_host(subdomain || SubdomainFu.preferred_mirror, host)
+ else
+ if has_subdomain?(subdomain) || preferred_mirror?(subdomain_from(host)) ||
+ (subdomain.nil? && has_subdomain?(subdomain_from(host)))
+ host
+ else
+ change_subdomain_of_host(SubdomainFu.preferred_mirror, host)
+ end
+ end
+ end
+
+ # Changes the subdomain of the host to whatever is passed in.
+ def self.change_subdomain_of_host(subdomain, host)
+ host = SubdomainFu.host_without_subdomain(host)
+ host = "#{subdomain}.#{host}" if subdomain
+ host
+ end
+
+ # Is this subdomain equivalent to the subdomain found in this host string?
+ def self.same_subdomain?(subdomain, host)
+ subdomain = nil unless subdomain
+ (subdomain == subdomain_from(host)) ||
+ (!has_subdomain?(subdomain) && !has_subdomain?(subdomain_from(host)))
+ end
+
+ def self.override_only_path?
+ self.override_only_path
+ end
+
+ def self.needs_rewrite?(subdomain, host)
+ case subdomain
+ when nil
+ #rewrite when there is a preferred mirror set and there is no subdomain on the host
+ return true if self.preferred_mirror && subdomain_from(host).nil?
+ return false
+ when false
+ h = subdomain_from(host)
+ #if the host has a subdomain
+ if !h.nil?
+ #rewrite when there is a subdomain in the host, and it is not a preferred mirror
+ return true if !preferred_mirror?(h)
+ #rewrite when there is a preferred mirror set and the subdomain of the host is not a mirror
+ return true if self.preferred_mirror && !is_mirror?(h)
+ #no rewrite if host already has mirror subdomain
+ #it { SubdomainFu.needs_rewrite?(false,"www.localhost").should be_false }
+ return false if is_mirror?(h)
+ end
+ return self.crazy_rewrite_rule(subdomain, host)
+ else
+ return self.crazy_rewrite_rule(subdomain, host)
+ end
+ end
+
+ #This is a black box of crazy! So I split some of the simpler logic out into the case statement above to make my brain happy!
+ def self.crazy_rewrite_rule(subdomain, host)
+ (!has_subdomain?(subdomain) && preferred_mirror?(subdomain) && !preferred_mirror?(subdomain_from(host))) ||
+ !same_subdomain?(subdomain, host)
+ end
+
+ def self.current_subdomain(request)
+ subdomain = request.subdomains(SubdomainFu.tld_size).join(".")
+ if has_subdomain?(subdomain)
+ subdomain
+ else
+ nil
+ end
+ end
+
+ #Enables subdomain-fu to more completely replace DHH's account_location plugin
+ def self.current_domain(request)
+ domain = ""
+ domain << request.subdomains[1..-1].join(".") + "." if request.subdomains.length > 1
+ domain << request.domain + request.port_string
+ end
+
+ module Controller
+ def self.included(controller)
+ controller.helper_method(:current_subdomain)
+ controller.helper_method(:current_domain)
+ end
+
+ protected
+ def current_subdomain
+ SubdomainFu.current_subdomain(request)
+ end
+ def current_domain
+ SubdomainFu.current_domain(request)
+ end
+ end
+end
diff --git a/vendor/plugins/subdomain-fu/lib/subdomain_fu/routing_extensions.rb b/vendor/plugins/subdomain-fu/lib/subdomain_fu/routing_extensions.rb
new file mode 100644
index 0000000..6dbf0d5
--- /dev/null
+++ b/vendor/plugins/subdomain-fu/lib/subdomain_fu/routing_extensions.rb
@@ -0,0 +1,61 @@
+# Thanks to Jamis Buck for ideas on this stuff
+# http://weblog.jamisbuck.org/2006/10/26/monkey-patching-rails-extending-routes-2
+# This is not yet a working part of SubdomainFu.
+
+module SubdomainFu
+ module RouteExtensions
+ def self.included(base)
+ base.alias_method_chain :recognition_conditions, :subdomain
+ end
+
+ def recognition_conditions_with_subdomain
+ result = recognition_conditions_without_subdomain
+ result << "conditions[:subdomain] === env[:subdomain]" if conditions[:subdomain] && conditions[:subdomain] != true && conditions[:subdomain] != false
+ result << "SubdomainFu.has_subdomain?(env[:subdomain])" if conditions[:subdomain] == true
+ result << "!SubdomainFu.has_subdomain?(env[:subdomain])" if conditions[:subdomain] == false
+ result
+ end
+ end
+
+ module RouteSetExtensions
+ def self.included(base)
+ base.alias_method_chain :extract_request_environment, :subdomain
+ end
+
+ def extract_request_environment_with_subdomain(request)
+ env = extract_request_environment_without_subdomain(request)
+ env.merge(:host => request.host, :domain => request.domain, :subdomain => SubdomainFu.current_subdomain(request))
+ end
+ end
+
+ module MapperExtensions
+ def quick_map(has_unless, *args, &block)
+ options = args.find{|a| a.is_a?(Hash)}
+ namespace_str = options ? options.delete(:namespace).to_s : args.join('_or_')
+ namespace_str += '_' unless namespace_str.blank?
+ mapped_exp = args.map(&:to_s).join('|')
+ conditions_hash = { :subdomain => ( has_unless ? /[^(#{mapped_exp})]/ : /(#{mapped_exp})/) }
+ with_options(:conditions => conditions_hash, :name_prefix => namespace_str, &block)
+ end
+ # Adds methods to Mapper to apply an options with a method. Example
+ # map.subdomain :blog { |blog| blog.resources :pages }
+ # or
+ # map.unless_subdomain :blog { |not_blog| not_blog.resources :people }
+ def subdomain(*args, &block)
+ quick_map(false, *args, &block)
+ end
+ def unless_subdomain(*args, &block)
+ quick_map(true, *args, &block)
+ end
+ end
+end
+
+ActionController::Routing::RouteSet::Mapper.send :include, SubdomainFu::MapperExtensions
+ActionController::Routing::RouteSet.send :include, SubdomainFu::RouteSetExtensions
+ActionController::Routing::Route.send :include, SubdomainFu::RouteExtensions
+
+# UrlRewriter::RESERVED_OPTIONS is only available in Rails >= 2.2
+# http://www.portallabs.com/blog/2008/12/02/fixing-subdomain_fu-with-named-routes-rails-22/
+if Rails::VERSION::MAJOR >= 2 and Rails::VERSION::MINOR >= 2
+ ActionController::UrlRewriter::RESERVED_OPTIONS << :subdomain
+end
diff --git a/vendor/plugins/subdomain-fu/lib/subdomain_fu/url_rewriter.rb b/vendor/plugins/subdomain-fu/lib/subdomain_fu/url_rewriter.rb
new file mode 100644
index 0000000..5066c5d
--- /dev/null
+++ b/vendor/plugins/subdomain-fu/lib/subdomain_fu/url_rewriter.rb
@@ -0,0 +1,48 @@
+module ActionController
+ module UrlWriter
+ def url_for_with_subdomains(options)
+ if SubdomainFu.needs_rewrite?(options[:subdomain], options[:host] || default_url_options[:host]) || options[:only_path] == false
+ options[:only_path] = false if SubdomainFu.override_only_path?
+ options[:host] = SubdomainFu.rewrite_host_for_subdomains(options.delete(:subdomain), options[:host] || default_url_options[:host])
+ else
+ options.delete(:subdomain)
+ end
+ url_for_without_subdomains(options)
+ end
+ alias_method_chain :url_for, :subdomains
+ end
+
+ class UrlRewriter #:nodoc:
+ private
+
+ def rewrite_url_with_subdomains(options)
+ if SubdomainFu.needs_rewrite?(options[:subdomain], (options[:host] || @request.host_with_port)) || options[:only_path] == false
+ options[:only_path] = false if SubdomainFu.override_only_path?
+ options[:host] = SubdomainFu.rewrite_host_for_subdomains(options.delete(:subdomain), options[:host] || @request.host_with_port)
+ # puts "options[:host]: #{options[:host].inspect}"
+ else
+ options.delete(:subdomain)
+ end
+ rewrite_url_without_subdomains(options)
+ end
+ alias_method_chain :rewrite_url, :subdomains
+ end
+
+ if Rails::VERSION::MAJOR >= 2 and Rails::VERSION::MINOR <= 1
+ # hack for http://www.portallabs.com/blog/2008/10/22/fixing-subdomain_fu-with-named-routes/
+ module Routing
+ module Optimisation
+ class PositionalArgumentsWithAdditionalParams
+ def guard_condition_with_subdomains
+ # don't allow optimisation if a subdomain is present - fixes a problem
+ # with the subdomain appearing in the query instead of being rewritten
+ # see http://mbleigh.lighthouseapp.com/projects/13148/tickets/8-improper-generated-urls-with-named-routes-for-a-singular-resource
+ guard_condition_without_subdomains + " && !args.last.has_key?(:subdomain)"
+ end
+
+ alias_method_chain :guard_condition, :subdomains
+ end
+ end
+ end
+ end
+end
diff --git a/vendor/plugins/subdomain-fu/rails/init.rb b/vendor/plugins/subdomain-fu/rails/init.rb
new file mode 100644
index 0000000..f8c620e
--- /dev/null
+++ b/vendor/plugins/subdomain-fu/rails/init.rb
@@ -0,0 +1,6 @@
+#Allow whatever Ruby Package tool is being used ot manage load paths. gem auto adds the gem's lib dir to load path.
+require 'subdomain-fu' unless defined?(SubdomainFu)
+
+ActionController::Base.send :include, SubdomainFu::Controller
+
+RAILS_DEFAULT_LOGGER.info("** SubdomainFu: initialized properly")
diff --git a/vendor/plugins/subdomain-fu/spec/spec.opts b/vendor/plugins/subdomain-fu/spec/spec.opts
new file mode 100644
index 0000000..49fd993
--- /dev/null
+++ b/vendor/plugins/subdomain-fu/spec/spec.opts
@@ -0,0 +1,7 @@
+--colour
+--format
+specdoc
+--loadby
+mtime
+--reverse
+--backtrace
\ No newline at end of file
diff --git a/vendor/plugins/subdomain-fu/spec/spec_helper.rb b/vendor/plugins/subdomain-fu/spec/spec_helper.rb
new file mode 100644
index 0000000..6b872fd
--- /dev/null
+++ b/vendor/plugins/subdomain-fu/spec/spec_helper.rb
@@ -0,0 +1,42 @@
+begin
+ require File.dirname(__FILE__) + '/../../../../spec/spec_helper'
+rescue LoadError
+ puts "You need to install rspec in your base app"
+ exit
+end
+
+plugin_spec_dir = File.dirname(__FILE__)
+ActiveRecord::Base.logger = Logger.new(plugin_spec_dir + "/debug.log")
+
+ActionController::Routing::Routes.draw do |map|
+ map.needs_subdomain '/needs_subdomain', :controller => "fu", :action => "awesome"
+ map.no_subdomain '/no_subdomain', :controller => "fu", :action => "lame"
+ map.needs_awesome '/needs_awesome', :controller => "fu", :action => "lame"
+
+ map.resources :foos do |fu|
+ fu.resources :bars
+ end
+
+ map.connect '/', :controller => "site", :action => "home", :conditions => {:subdomain => false}
+ map.connect '/', :controller => "app", :action => "home", :conditions => {:subdomain => true}
+ map.connect '/', :controller => "mobile", :action => "home", :conditions => {:subdomain => "m"}
+
+ map.connect '/subdomain_here', :controller => "app", :action => "success", :conditions => {:subdomain => true}
+ map.connect '/no_subdomain_here', :controller => "site", :action => "success", :conditions => {:subdomain => false}
+ map.connect '/m_subdomain_here', :controller => "mobile", :action => "success", :conditions => {:subdomain => "m"}
+ map.connect '/numbers_only_here', :controller => "numbers", :action => "success", :conditions => {:subdomain => /[0-9]+/}
+
+ map.connect '/:controller/:action/:id'
+end
+
+class Paramed
+ def initialize(param)
+ @param = param
+ end
+
+ def to_param
+ @param || "param"
+ end
+end
+
+include ActionController::UrlWriter
diff --git a/vendor/plugins/subdomain-fu/spec/subdomain_fu_spec.rb b/vendor/plugins/subdomain-fu/spec/subdomain_fu_spec.rb
new file mode 100644
index 0000000..574cc25
--- /dev/null
+++ b/vendor/plugins/subdomain-fu/spec/subdomain_fu_spec.rb
@@ -0,0 +1,244 @@
+require File.dirname(__FILE__) + '/spec_helper'
+
+describe "SubdomainFu" do
+ before do
+ SubdomainFu.tld_sizes = SubdomainFu::DEFAULT_TLD_SIZES.dup
+ SubdomainFu.mirrors = SubdomainFu::DEFAULT_MIRRORS.dup
+ SubdomainFu.preferred_mirror = nil
+ end
+
+ describe "TLD Sizes" do
+ before do
+ SubdomainFu.tld_sizes = SubdomainFu::DEFAULT_TLD_SIZES.dup
+ end
+
+ it { SubdomainFu.tld_sizes.should be_kind_of(Hash) }
+
+ it "should have default values for development, test, and production" do
+ SubdomainFu.tld_sizes[:development].should == 0
+ SubdomainFu.tld_sizes[:test].should == 0
+ SubdomainFu.tld_sizes[:production].should == 1
+ end
+
+ it "#tld_size should be for the current environment" do
+ SubdomainFu.tld_size.should == SubdomainFu.tld_sizes[RAILS_ENV.to_sym]
+ end
+
+ it "should be able to be set for the current environment" do
+ SubdomainFu.tld_size = 5
+ SubdomainFu.tld_size.should == 5
+ SubdomainFu.tld_sizes[:test].should == 5
+ end
+ end
+
+ describe "#has_subdomain?" do
+ it "should be true for non-mirrored subdomains" do
+ SubdomainFu.has_subdomain?("awesome").should be_true
+ end
+
+ it "should be false for mirrored subdomains" do
+ SubdomainFu.has_subdomain?(SubdomainFu.mirrors.first).should be_false
+ end
+
+ it "shoud be false for a nil or blank subdomain" do
+ SubdomainFu.has_subdomain?("").should be_false
+ SubdomainFu.has_subdomain?(nil).should be_false
+ SubdomainFu.has_subdomain?(false).should be_false
+ end
+ end
+
+ describe "#subdomain_from" do
+ it "should return the subdomain based on the TLD of the current environment" do
+ SubdomainFu.subdomain_from("awesome.localhost").should == "awesome"
+ SubdomainFu.tld_size = 2
+ SubdomainFu.subdomain_from("awesome.localhost.co.uk").should == "awesome"
+ SubdomainFu.tld_size = 1
+ SubdomainFu.subdomain_from("awesome.localhost.com").should == "awesome"
+ SubdomainFu.tld_size = 0
+ end
+
+ it "should join deep subdomains with a period" do
+ SubdomainFu.subdomain_from("awesome.coolguy.localhost").should == "awesome.coolguy"
+ end
+
+ it "should return nil for no subdomain" do
+ SubdomainFu.subdomain_from("localhost").should be_nil
+ end
+ end
+
+ it "#host_without_subdomain should chop of the subdomain and return the rest" do
+ SubdomainFu.host_without_subdomain("awesome.localhost:3000").should == "localhost:3000"
+ SubdomainFu.host_without_subdomain("something.awful.localhost:3000").should == "localhost:3000"
+ end
+
+ describe "#preferred_mirror?" do
+ describe "when preferred_mirror is false" do
+ before do
+ SubdomainFu.preferred_mirror = false
+ end
+
+ it "should return true for false" do
+ SubdomainFu.preferred_mirror?(false).should be_true
+ end
+ end
+ end
+
+ describe "#rewrite_host_for_subdomains" do
+ it "should not change the same subdomain" do
+ SubdomainFu.rewrite_host_for_subdomains("awesome","awesome.localhost").should == "awesome.localhost"
+ end
+
+ it "should not change an equivalent (mirrored) subdomain" do
+ SubdomainFu.rewrite_host_for_subdomains("www","localhost").should == "localhost"
+ end
+
+ it "should change the subdomain if it's different" do
+ SubdomainFu.rewrite_host_for_subdomains("cool","www.localhost").should == "cool.localhost"
+ end
+
+ it "should remove the subdomain if passed false when it's not a mirror" do
+ SubdomainFu.rewrite_host_for_subdomains(false,"cool.localhost").should == "localhost"
+ end
+
+ it "should not remove the subdomain if passed false when it is a mirror" do
+ SubdomainFu.rewrite_host_for_subdomains(false,"www.localhost").should == "www.localhost"
+ end
+
+ it "should not remove the subdomain if passed nil when it's not a mirror" do
+ SubdomainFu.rewrite_host_for_subdomains(nil,"cool.localhost").should == "cool.localhost"
+ end
+
+ describe "when preferred_mirror is false" do
+ before do
+ SubdomainFu.preferred_mirror = false
+ end
+
+ it "should remove the subdomain if passed false when it is a mirror" do
+ SubdomainFu.rewrite_host_for_subdomains(false,"www.localhost").should == "localhost"
+ end
+
+ it "should not remove the subdomain if passed nil when it's not a mirror" do
+ SubdomainFu.rewrite_host_for_subdomains(nil,"cool.localhost").should == "cool.localhost"
+ end
+ end
+ end
+
+ describe "#change_subdomain_of_host" do
+ it "should change it if passed a different one" do
+ SubdomainFu.change_subdomain_of_host("awesome","cool.localhost").should == "awesome.localhost"
+ end
+
+ it "should remove it if passed nil" do
+ SubdomainFu.change_subdomain_of_host(nil,"cool.localhost").should == "localhost"
+ end
+
+ it "should add it if there isn't one" do
+ SubdomainFu.change_subdomain_of_host("awesome","localhost").should == "awesome.localhost"
+ end
+ end
+
+ describe "#current_subdomain" do
+ it "should return the current subdomain if there is one" do
+ request = mock("request", :subdomains => ["awesome"])
+ SubdomainFu.current_subdomain(request).should == "awesome"
+ end
+
+ it "should return nil if there's no subdomain" do
+ request = mock("request", :subdomains => [])
+ SubdomainFu.current_subdomain(request).should be_nil
+ end
+
+ it "should return nil if the current subdomain is a mirror" do
+ request = mock("request", :subdomains => ["www"])
+ SubdomainFu.current_subdomain(request).should be_nil
+ end
+
+ it "should return the whole thing (including a .) if there's multiple subdomains" do
+ request = mock("request", :subdomains => ["awesome","rad"])
+ SubdomainFu.current_subdomain(request).should == "awesome.rad"
+ end
+ end
+
+ describe "#current_domain" do
+ it "should return the current domain if there is one" do
+ request = mock("request", :subdomains => [], :domain => "example.com", :port_string => "")
+ SubdomainFu.current_domain(request).should == "example.com"
+ end
+
+ it "should return empty string if there is no domain" do
+ request = mock("request", :subdomains => [], :domain => "", :port_string => "")
+ SubdomainFu.current_domain(request).should == ""
+ end
+
+ it "should return the current domain if there is only one level of subdomains" do
+ request = mock("request", :subdomains => ["www"], :domain => "example.com", :port_string => "")
+ SubdomainFu.current_domain(request).should == "example.com"
+ end
+
+ it "should return everything but the first level of subdomain when there are multiple levels of subdomains" do
+ request = mock("request", :subdomains => ["awesome","rad","cheese","chevy","ford"], :domain => "example.com", :port_string => "")
+ SubdomainFu.current_domain(request).should == "rad.cheese.chevy.ford.example.com"
+ end
+
+ it "should return the domain with port if port is given" do
+ request = mock("request", :subdomains => ["awesome","rad","cheese","chevy","ford"], :domain => "example.com", :port_string => ":3000")
+ SubdomainFu.current_domain(request).should == "rad.cheese.chevy.ford.example.com:3000"
+ end
+ end
+
+ describe "#same_subdomain?" do
+ it { SubdomainFu.same_subdomain?("www","www.localhost").should be_true }
+ it { SubdomainFu.same_subdomain?("www","localhost").should be_true }
+ it { SubdomainFu.same_subdomain?("awesome","www.localhost").should be_false }
+ it { SubdomainFu.same_subdomain?("cool","awesome.localhost").should be_false }
+ it { SubdomainFu.same_subdomain?(nil,"www.localhost").should be_true }
+ it { SubdomainFu.same_subdomain?("www","awesome.localhost").should be_false }
+ end
+
+ describe "#needs_rewrite?" do
+ it { SubdomainFu.needs_rewrite?("www","www.localhost").should be_false }
+ it { SubdomainFu.needs_rewrite?("www","localhost").should be_false }
+ it { SubdomainFu.needs_rewrite?("awesome","www.localhost").should be_true }
+ it { SubdomainFu.needs_rewrite?("cool","awesome.localhost").should be_true }
+ it { SubdomainFu.needs_rewrite?(nil,"www.localhost").should be_false }
+ it { SubdomainFu.needs_rewrite?(nil,"awesome.localhost").should be_false }
+ it { SubdomainFu.needs_rewrite?(false,"awesome.localhost").should be_true }
+ it { SubdomainFu.needs_rewrite?(false,"www.localhost").should be_false }
+ it { SubdomainFu.needs_rewrite?("www","awesome.localhost").should be_true }
+
+ describe "when preferred_mirror is false" do
+ before do
+ SubdomainFu.preferred_mirror = false
+ end
+
+ it { SubdomainFu.needs_rewrite?("www","www.localhost").should be_false }
+ it { SubdomainFu.needs_rewrite?("www","localhost").should be_false }
+ it { SubdomainFu.needs_rewrite?("awesome","www.localhost").should be_true }
+ it { SubdomainFu.needs_rewrite?("cool","awesome.localhost").should be_true }
+ it { SubdomainFu.needs_rewrite?(nil,"www.localhost").should be_false }
+ it { SubdomainFu.needs_rewrite?(nil,"awesome.localhost").should be_false }
+ it { SubdomainFu.needs_rewrite?(false,"awesome.localhost").should be_true }
+ #Only one different from default set of tests
+ it { SubdomainFu.needs_rewrite?(false,"www.localhost").should be_true }
+ it { SubdomainFu.needs_rewrite?("www","awesome.localhost").should be_true }
+ end
+
+ describe "when preferred_mirror is string" do
+ before do
+ SubdomainFu.preferred_mirror = "www"
+ end
+
+ it { SubdomainFu.needs_rewrite?("www","www.localhost").should be_false }
+ it { SubdomainFu.needs_rewrite?("awesome","www.localhost").should be_true }
+ # Following is different from default set of tests
+ it { SubdomainFu.needs_rewrite?("www","localhost").should be_true }
+ it { SubdomainFu.needs_rewrite?("cool","awesome.localhost").should be_true }
+ it { SubdomainFu.needs_rewrite?(nil,"www.localhost").should be_false }
+ it { SubdomainFu.needs_rewrite?(nil,"awesome.localhost").should be_false }
+ it { SubdomainFu.needs_rewrite?(false,"awesome.localhost").should be_true }
+ it { SubdomainFu.needs_rewrite?(false,"www.localhost").should be_false }
+ it { SubdomainFu.needs_rewrite?("www","awesome.localhost").should be_true }
+ end
+
+ end
+end
diff --git a/vendor/plugins/subdomain-fu/spec/url_rewriter_spec.rb b/vendor/plugins/subdomain-fu/spec/url_rewriter_spec.rb
new file mode 100644
index 0000000..f35820f
--- /dev/null
+++ b/vendor/plugins/subdomain-fu/spec/url_rewriter_spec.rb
@@ -0,0 +1,149 @@
+require File.dirname(__FILE__) + '/spec_helper'
+
+describe "SubdomainFu URL Writing" do
+ before do
+ SubdomainFu.tld_size = 1
+ SubdomainFu.mirrors = SubdomainFu::DEFAULT_MIRRORS.dup
+ SubdomainFu.override_only_path = true
+ SubdomainFu.preferred_mirror = nil
+ default_url_options[:host] = "example.com"
+ end
+
+ describe "#url_for" do
+ it "should be able to add a subdomain" do
+ url_for(:controller => "something", :action => "other", :subdomain => "awesome").should == "http://awesome.example.com/something/other"
+ end
+
+ it "should be able to remove a subdomain" do
+ url_for(:controller => "something", :action => "other", :subdomain => false, :host => "awesome.example.com").should == "http://example.com/something/other"
+ end
+
+ it "should not change a mirrored subdomain" do
+ url_for(:controller => "something", :action => "other", :subdomain => false, :host => "www.example.com").should == "http://www.example.com/something/other"
+ end
+
+ it "should should not force the full url with :only_path if override_only_path is false (default)" do
+ SubdomainFu.override_only_path = false
+ url_for(:controller => "something", :action => "other", :subdomain => "awesome", :only_path => true).should == "/something/other"
+ end
+
+ it "should should force the full url, even with :only_path if override_only_path is true" do
+ SubdomainFu.override_only_path = true
+ url_for(:controller => "something", :action => "other", :subdomain => "awesome", :only_path => true).should == "http://awesome.example.com/something/other"
+ end
+ end
+
+ describe "Standard Routes" do
+ it "should be able to add a subdomain" do
+ needs_subdomain_url(:subdomain => "awesome").should == "http://awesome.example.com/needs_subdomain"
+ end
+
+ it "should be able to remove a subdomain" do
+ default_url_options[:host] = "awesome.example.com"
+ needs_subdomain_url(:subdomain => false).should == "http://example.com/needs_subdomain"
+ end
+
+ it "should not change a mirrored subdomain" do
+ default_url_options[:host] = "www.example.com"
+ needs_subdomain_url(:subdomain => false).should == "http://www.example.com/needs_subdomain"
+ end
+
+ it "should should force the full url, even with _path" do
+ needs_subdomain_path(:subdomain => "awesome").should == needs_subdomain_url(:subdomain => "awesome")
+ end
+
+ it "should not force the full url if it's the same as the current subdomain" do
+ default_url_options[:host] = "awesome.example.com"
+ needs_subdomain_path(:subdomain => "awesome").should == "/needs_subdomain"
+ end
+
+ it "should force the full url if it's a different subdomain" do
+ default_url_options[:host] = "awesome.example.com"
+ needs_subdomain_path(:subdomain => "crazy").should == "http://crazy.example.com/needs_subdomain"
+ end
+
+ it "should not force the full url if the current subdomain is nil and so is the target" do
+ needs_subdomain_path(:subdomain => nil).should == "/needs_subdomain"
+ end
+
+ it "should not force the full url if no :subdomain option is given" do
+ needs_subdomain_path.should == "/needs_subdomain"
+ default_url_options[:host] = "awesome.example.com"
+ needs_subdomain_path.should == "/needs_subdomain"
+ end
+ end
+
+ describe "Resourced Routes" do
+ it "should be able to add a subdomain" do
+ foo_path(:id => "something", :subdomain => "awesome").should == "http://awesome.example.com/foos/something"
+ end
+
+ it "should be able to remove a subdomain" do
+ default_url_options[:host] = "awesome.example.com"
+ foo_path(:id => "something", :subdomain => false).should == "http://example.com/foos/something"
+ end
+
+ it "should work when passed in a paramable object" do
+ foo_path(Paramed.new("something"), :subdomain => "awesome").should == "http://awesome.example.com/foos/something"
+ end
+
+ it "should work when passed in a paramable object" do
+ foo_path(Paramed.new("something"), :subdomain => "awesome").should == "http://awesome.example.com/foos/something"
+ end
+
+ it "should work when passed in a paramable object and no subdomain to a _path" do
+ default_url_options[:host] = "awesome.example.com"
+ foo_path(Paramed.new("something")).should == "/foos/something"
+ end
+
+ it "should work when passed in a paramable object and no subdomain to a _url" do
+ default_url_options[:host] = "awesome.example.com"
+ foo_url(Paramed.new("something")).should == "http://awesome.example.com/foos/something"
+ end
+
+ it "should work on nested resource collections" do
+ foo_bars_path(Paramed.new("something"), :subdomain => "awesome").should == "http://awesome.example.com/foos/something/bars"
+ end
+
+ it "should work on nested resource members" do
+ foo_bar_path(Paramed.new("something"),Paramed.new("else"), :subdomain => "awesome").should == "http://awesome.example.com/foos/something/bars/else"
+ end
+ end
+
+ describe "Preferred Mirror" do
+ before do
+ SubdomainFu.preferred_mirror = "www"
+ SubdomainFu.override_only_path = true
+ end
+
+ it "should switch to the preferred mirror instead of no subdomain" do
+ default_url_options[:host] = "awesome.example.com"
+ needs_subdomain_url(:subdomain => false).should == "http://www.example.com/needs_subdomain"
+ end
+
+ it "should switch to the preferred mirror automatically" do
+ default_url_options[:host] = "example.com"
+ needs_subdomain_url.should == "http://www.example.com/needs_subdomain"
+ end
+
+ it "should work when passed in a paramable object and no subdomain to a _url" do
+ default_url_options[:host] = "awesome.example.com"
+ foo_url(Paramed.new("something")).should == "http://awesome.example.com/foos/something"
+ end
+
+ it "should force a switch to no subdomain on a mirror if preferred_mirror is false" do
+ SubdomainFu.preferred_mirror = false
+ default_url_options[:host] = "www.example.com"
+ needs_subdomain_url(:subdomain => false).should == "http://example.com/needs_subdomain"
+ end
+
+ after do
+ SubdomainFu.preferred_mirror = nil
+ end
+ end
+
+ after do
+ SubdomainFu.tld_size = 0
+ default_url_options[:host] = "localhost"
+ end
+end
diff --git a/vendor/plugins/subdomain-fu/subdomain-fu.gemspec b/vendor/plugins/subdomain-fu/subdomain-fu.gemspec
new file mode 100644
index 0000000..d882b98
--- /dev/null
+++ b/vendor/plugins/subdomain-fu/subdomain-fu.gemspec
@@ -0,0 +1,55 @@
+# Generated by jeweler
+# DO NOT EDIT THIS FILE DIRECTLY
+# Instead, edit Jeweler::Tasks in Rakefile, and run the gemspec command
+# -*- encoding: utf-8 -*-
+
+Gem::Specification.new do |s|
+ s.name = %q{subdomain-fu}
+ s.version = "0.5.4"
+
+ s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
+ s.authors = ["Michael Bleigh"]
+ s.date = %q{2010-01-18}
+ s.description = %q{SubdomainFu is a Rails plugin to provide all of the basic functionality necessary to handle multiple subdomain applications (such as Basecamp-esque subdomain accounts and more).}
+ s.email = %q{michael@intridea.com}
+ s.extra_rdoc_files = [
+ "README.rdoc"
+ ]
+ s.files = [
+ "CHANGELOG",
+ "MIT-LICENSE",
+ "README.rdoc",
+ "Rakefile",
+ "VERSION.yml",
+ "lib/subdomain-fu.rb",
+ "lib/subdomain_fu/routing_extensions.rb",
+ "lib/subdomain_fu/url_rewriter.rb",
+ "rails/init.rb",
+ "spec/spec.opts",
+ "spec/spec_helper.rb",
+ "spec/subdomain_fu_spec.rb",
+ "spec/url_rewriter_spec.rb"
+ ]
+ s.homepage = %q{http://github.com/mbleigh/subdomain-fu}
+ s.rdoc_options = ["--charset=UTF-8"]
+ s.require_paths = ["lib"]
+ s.rubyforge_project = %q{subdomain-fu}
+ s.rubygems_version = %q{1.3.5}
+ s.summary = %q{SubdomainFu is a Rails plugin that provides subdomain routing and URL writing helpers.}
+ s.test_files = [
+ "spec/spec_helper.rb",
+ "spec/subdomain_fu_spec.rb",
+ "spec/url_rewriter_spec.rb"
+ ]
+
+ if s.respond_to? :specification_version then
+ current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION
+ s.specification_version = 3
+
+ if Gem::Version.new(Gem::RubyGemsVersion) >= Gem::Version.new('1.2.0') then
+ else
+ end
+ else
+ end
+end
+
|
macbury/webpraca
|
537c2d4c11f2cd48bfe81e3ada5966764e171d94
|
English translation
|
diff --git a/.gitignore b/.gitignore
index dd41b69..14e813c 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,14 +1,13 @@
.DS_Store
log/*.log
tmp/**/*
public/*.xml.gz
public/images/captchas/*
config/database.yml
config/mailer.yml
config/exception_notifer.yml
config/exception_notifier.yml
config/website_config.yml
config/micro_feed.yml
config/newrelic.yml
-config/deploy.rb
db/*.sqlite3
diff --git a/README b/README
index e6235bd..9549f37 100644
--- a/README
+++ b/README
@@ -1,20 +1,28 @@
-= Instalacja
+= Configuration
+
+1. database info (config/database.yml)
+2. email for exception notificator(config/exception_notifier.yml)
+3. email configuration for mailer(config/mailer.yml)
+4. configuration for streams (config/micro_feed.yml)
+5. timezone and language(English or Polish) in config/environment.rb
+
+= Instalation
1. rake db:create
2. rake db:migrate
3. rake db:seed
4. rake webpraca:admin:create
= Running test suite
== Specs
rake gems:install RAILS_ENV=test
rake spec
== Cucumber with capybara
rake gems:install RAILS_ENV=cucumber
rake db:test:prepare # only needed if test database does not exist
cucumber features/
diff --git a/app/controllers/applicants_controller.rb b/app/controllers/applicants_controller.rb
index ec6611a..07f0572 100644
--- a/app/controllers/applicants_controller.rb
+++ b/app/controllers/applicants_controller.rb
@@ -1,36 +1,36 @@
class ApplicantsController < ApplicationController
before_filter :get_job
ads_pos :right
validates_captcha :except => :download
def create
@applicant = @job.applicants.new(params[:applicant])
if @applicant.save
- flash[:notice] = "Twoja aplikacja zostaÅa wysÅana"
+ flash[:notice] = t('flash.notice.application_sended')
redirect_to seo_job_path(@job)
else
render :action => 'new'
end
end
def new
@applicant = @job.applicants.new
end
def download
@applicant = @job.applicants.find_by_token!(params[:id])
send_file @applicant.cv.path,
:type => @applicant.cv_content_type,
:filename => @applicant.email.gsub('@', '(at)').gsub('.', '(dot)') + File.extname(@applicant.cv_file_name)
#:x_sendfile => true
end
protected
def get_job
@job = Job.active.find_by_permalink!(params[:job_id])
redirect_to seo_job_path(@job) unless @job.apply_online
- @page_title = [@job.title, "Aplikuj online"]
+ @page_title = [@job.title, t('applicant.title')]
end
end
diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb
index ee5a137..93a9ab9 100644
--- a/app/controllers/application_controller.rb
+++ b/app/controllers/application_controller.rb
@@ -1,117 +1,117 @@
class ApplicationController < ActionController::Base
include ExceptionNotifiable
helper :all # include all helpers, all the time
protect_from_forgery # See ActionController::RequestForgeryProtection for details
filter_parameter_logging :password, :password_confirmation
helper_method :current_user_session, :current_user, :logged_in?, :own?
before_filter :staging_authentication, :seo, :user_for_authorization
def rescue_action_in_public(exception)
case exception
when ActiveRecord::RecordNotFound
render_404
when ActionController::RoutingError
render_404
when ActionController::UnknownController
render_404
when ActionController::UnknownAction
render_404
else
render_500
end
end
protected
def render_404
@page_title = ["BÅÄ
d 404", "Nie znaleziono strony"]
render :template => "shared/error_404", :layout => 'application', :status => :not_found
end
def render_500
@page_title = ["BÅÄ
d 500", "CoÅ poszÅo nie tak"]
render :template => "shared/error_500", :layout => 'application', :status => :internal_server_error
end
def not_for_production
redirect_to root_path if Rails.env == "production"
end
# Ads Position
# :bottom, :right, :none
def self.ads_pos(position, options = {})
before_filter(options) do |controller|
controller.instance_variable_set('@ads_pos', position)
end
end
def user_for_authorization
Authorization.current_user = self.current_user
end
def permission_denied
- flash[:error] = "Nie masz wystarczajÄ
cych uprawnieÅ aby móc odwiedziÄ tÄ
stronÄ"
+ flash[:error] = t('flash.error.access_denied')
redirect_to root_url
end
def seo
@ads_pos = :bottom
set_meta_tags :description => WebSiteConfig['website']['description'],
:keywords => WebSiteConfig['website']['tags']
end
def staging_authentication
if ENV['RAILS_ENV'] == 'staging'
authenticate_or_request_with_http_basic do |user_name, password|
user_name == "change this" && password == "and this"
end
end
end
def current_user_session
@current_user_session ||= UserSession.find
return @current_user_session
end
def current_user
@current_user ||= self.current_user_session && self.current_user_session.user
return @current_user
end
def logged_in?
!self.current_user.nil?
end
def own?(object)
logged_in? && self.current_user.own?(object)
end
def store_location
session[:return_to] = request.request_uri
end
def redirect_back_or_default
redirect_to session[:return_to] || admin_path
session[:return_to] = nil
end
def login_required
unless logged_in?
respond_to do |format|
format.html do
- flash[:error] = "Musisz siÄ zalogowaÄ aby móc objrzeÄ tÄ
strone"
+ flash[:error] = t('flash.error.access_denied')
store_location
redirect_to login_path
end
format.js { render :js => "window.location = #{login_path.inspect};" }
end
else
- @page_title = ["Panel administracyjny"]
+ @page_title = [t('title.admin')]
end
end
end
\ No newline at end of file
diff --git a/app/controllers/contact_controller.rb b/app/controllers/contact_controller.rb
index 3543fe8..85d310b 100644
--- a/app/controllers/contact_controller.rb
+++ b/app/controllers/contact_controller.rb
@@ -1,22 +1,22 @@
class ContactController < ApplicationController
validates_captcha_of ContactHandler
ads_pos :right
def new
@contact_handler = ContactHandler.new
@contact_handler.job_id = params[:job_id]
end
def create
@contact_handler = ContactHandler.new(params[:contact_handler])
if @contact_handler.valid?
ContactMailer.deliver_contact_notification(@contact_handler)
- flash[:notice] = 'DziÄkujemy za wiadomoÅÄ!'
+ flash[:notice] = t('flash.notice.contact_sended')
redirect_to root_path
else
render :action => "new"
end
end
end
\ No newline at end of file
diff --git a/app/controllers/jobs_controller.rb b/app/controllers/jobs_controller.rb
index eb0f605..ceae93f 100644
--- a/app/controllers/jobs_controller.rb
+++ b/app/controllers/jobs_controller.rb
@@ -1,196 +1,196 @@
class JobsController < ApplicationController
validates_captcha :only => [:create, :new]
ads_pos :bottom
ads_pos :right, :except => [:home, :index, :search]
ads_pos :none, :only => [:home]
def home
set_meta_tags :title => t('home.title'),
:separator => " - "
query = Job.active.search
@recent_jobs = query.all(:order => "created_at DESC", :limit => 15, :include => [:localization, :category])
@top_jobs = query.all(:order => "rank DESC, created_at DESC", :limit => 15, :include => [:localization, :category])
end
# GET /jobs
# GET /jobs.xml
def index
@query = Job.active.search
options = {
:page => params[:page],
:per_page => 35,
:order => "created_at DESC, rank DESC",
:include => [:localization, :category]
}
- if params[:order] =~ /najpopularniejsze/i
+ if params[:order] =~ /popular/i
@page_title = [t('title.popular')]
@order = :rank
options[:order] = "rank DESC, created_at DESC"
else
@order = :created_at
@page_title = [t('title.latest')]
options[:order] = "created_at DESC, rank DESC"
end
if params[:language]
@language = Language.find_by_permalink!(params[:language])
@page_title << @language.name.downcase
@query.language_id_is(@language.id)
end
if params[:category]
@category = Category.find_by_permalink!(params[:category])
@page_title << @category.name.downcase
@query.category_id_is(@category.id)
end
if params[:localization]
@localization = Localization.find_by_permalink!(params[:localization])
@page_title << @localization.name.downcase
@query.localization_id_is(@localization.id)
end
if params[:framework]
@framework = Framework.find_by_permalink!(params[:framework])
@page_title << @framework.name.downcase
options[:include] << :framework
@query.framework_id_is(@framework.id)
end
if params[:type_id]
@type_id = JOB_TYPES.index(params[:type_id]) || 0
@page_title << JOB_TYPES[@type_id].downcase
@query.type_id_is(@type_id)
end
@jobs = @query.paginate(options)
respond_to do |format|
format.html # index.html.erb
format.rss
format.atom
end
end
def search
@page_title = [t('title.search')]
@search = Job.active.search(params[:search])
if params[:search]
@page_title = [t('title.finded_jobs')]
@jobs = @search.paginate( :page => params[:page],
:per_page => 30,
:order => "created_at DESC, rank DESC" )
end
respond_to do |format|
format.html
format.rss { render :action => "index" }
format.atom { render :action => "index" }
end
end
# GET /jobs/1
# GET /jobs/1.xml
def show
@job = Job.find_by_permalink!(params[:id])
@job.visited_by(request.remote_ip)
@category = @job.category
@page_title = [t('title.jobs'), @job.category.name.downcase, @job.localization.name.downcase, @job.company_name.downcase, @job.title.downcase]
@tags = WebSiteConfig['website']['tags'].split(',').map(&:strip) + [@job.category.name, @job.localization.name, @job.company_name]
@tags << JOB_TYPES[@job.type_id]
unless @job.framework.nil?
@tags << @job.framework.name
@page_title.insert(1, @job.framework.name)
end
unless @job.language.nil?
@page_title.insert(1, @job.language.name)
@tags << @job.language.name
end
set_meta_tags :keywords => @tags.join(', ')
respond_to do |format|
format.html # show.html.erb
end
end
# GET /jobs/new
# GET /jobs/new.xml
def new
@job = Job.new
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @job }
end
end
# POST /jobs
# POST /jobs.xml
def create
@job = Job.new(params[:job])
respond_to do |format|
if @job.save
flash[:notice] = t('flash.notice.email_verification')
format.html { redirect_to(@job) }
format.xml { render :xml => @job, :status => :created, :location => @job }
else
format.html { render :action => "new" }
format.xml { render :xml => @job.errors, :status => :unprocessable_entity }
end
end
end
# GET /jobs/1/edit
def edit
@job = Job.find_by_permalink_and_token!(params[:id], params[:token])
render :action => "new"
end
# PUT /jobs/1
# PUT /jobs/1.xml
def update
@job = Job.find_by_permalink_and_token!(params[:id], params[:token])
respond_to do |format|
if @job.update_attributes(params[:job])
flash[:notice] = t('flash.notice.job_updated')
format.html { redirect_to(@job) }
format.xml { head :ok }
else
format.html { render :action => "new" }
format.xml { render :xml => @job.errors, :status => :unprocessable_entity }
end
end
end
def publish
@job = Job.find_by_permalink_and_token!(params[:id], params[:token])
unless @job.published
@job.publish!
flash[:notice] = t('flash.notice.job_published')
end
redirect_to @job
end
# DELETE /jobs/1
# DELETE /jobs/1.xml
def destroy
@job = Job.find_by_permalink_and_token!(params[:id], params[:token])
@job.destroy
flash[:notice] = t('flash.notice.job_deleted')
respond_to do |format|
format.html { redirect_to(jobs_url) }
format.xml { head :ok }
end
end
end
diff --git a/app/models/job.rb b/app/models/job.rb
index 5273fe4..07b5989 100644
--- a/app/models/job.rb
+++ b/app/models/job.rb
@@ -1,178 +1,178 @@
JOB_TYPES = ["freelance", "full_time", "free", "practice"]
JOB_ETAT = 1;
JOB_RANK_VALUES = {
:default => 0.3,
:price => 0.8,
:krs => 0.6,
:nip => 0.5,
:regon => 0.6,
:framework_id => 0.7,
:language_id => 0.7,
:website => 0.4,
:apply_online => 0.3
}
class Job < ActiveRecord::Base
include ActionController::UrlWriter
xss_terminate
has_permalink :title
named_scope :active, :conditions => ["((jobs.end_at >= ?) AND (jobs.published = ?))", Date.current, true]
named_scope :old, :conditions => ["jobs.end_at < ?", Date.current]
named_scope :has_text, lambda { |text| { :conditions => ["((jobs.title ILIKE ?) OR (jobs.description ILIKE ?))", "%#{text}%", "%#{text}%"] } }
validates_presence_of :title, :description, :email, :company_name, :localization_id, :category_id
validates_length_of :title, :within => 3..255
validates_length_of :description, :within => 10..5000
validates_inclusion_of :type_id, :in => 0..JOB_TYPES.size-1
validates_inclusion_of :availability_time, :in => 1..60
validates_numericality_of :price_from,
:greater_than => 0,
:unless => Proc.new { |j| j.price_from.nil? }
validates_numericality_of :price_to,
:greater_than => 0,
:unless => Proc.new { |j| j.price_to.nil? }
validates_format_of :email, :with => /([a-z0-9_.-]+)@([a-z0-9-]+)\.([a-z.]+)/i
validates_format_of :website, :with => /(^$)|(^(http|https):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(([0-9]{1,5})?\/.*)?$)/ix
validates_format_of :regon,
:with => /(^$)|(^[0-9]{7,14}$)/
validates_format_of :nip,
:with => /(^$)|(^\d{2,3}-\d{2,3}-\d{2,3}-\d{2,3}$)/
validates_format_of :krs,
:with => /(^$)|(^\d{10})$/
belongs_to :framework
belongs_to :localization
belongs_to :category
belongs_to :language
has_many :applicants, :dependent => :delete_all
has_many :visits, :dependent => :delete_all
attr_protected :rank, :permalink, :end_at, :token, :published
attr_accessor :framework_name, :localization_name
before_create :create_from_name, :generate_token
before_save :calculate_rank
after_create :send_notification
def self.find_grouped_by_type
return Job.active.count(:type_id, :group => "type_id")
end
def send_notification
JobMailer.deliver_job_posted(self)
end
def generate_token
alphanumerics = ('a'..'z').to_a.concat(('A'..'Z').to_a.concat(('0'..'9').to_a))
salt = alphanumerics.sort_by{rand}.to_s[0..1024]
self.token = Digest::SHA1.hexdigest("--#{salt}--#{self.id}--#{Date.current}--")
generate_token unless Job.find_by_token(self.token).nil?
end
def calculate_rank
self.rank = 1.0
self.rank += visits_count * 0.001 unless visits_count.nil?
self.rank += applicants_count * 0.01 unless applicants_count.nil?
[:regon, :nip, :krs, :framework_id, :website, :apply_online, :language_id].each do |attribute|
val = send(attribute)
inc = JOB_RANK_VALUES[attribute] || JOB_RANK_VALUES[:default]
self.rank += inc unless (val.nil? || (val.class == String && val.empty?) || (val.class == TrueClass))
end
if pay_band?
self.rank += JOB_RANK_VALUES[:price]
price = price_from || price_to
if price >= 10_000 # ciekawe czy ktoÅ da tyle :P
self.rank += 0.8
elsif price >= 7000
self.rank += 0.7
elsif price >= 5000
self.rank += 0.6
elsif price >= 3000
self.rank += 0.3
elsif price < 2000
if self.type_id == JOB_ETAT
self.rank -= 0.6 # bo nikt za grosze nie chce pracowaÄ
else
self.rank += 0.3 # chyba że to biedny student
end
end
end
end
def pay_band?
((!self.price_from.nil? && self.price_from > 0) || (!self.price_to.nil? && self.price_to > 0))
end
def create_from_name
unless (self.framework_name.nil? || self.framework_name.blank?)
framework = Framework.name_like(self.framework_name).first
framework = Framework.create(:name => self.framework_name) if framework.nil?
self.framework = framework
end
unless (self.localization_name.nil? || self.localization_name.blank?)
localization = Localization.name_like(self.localization_name).first
localization = Localization.create(:name => self.localization_name) if localization.nil?
self.localization = localization
end
end
def availability_time
date = created_at.nil? ? Date.current.to_date : created_at.to_date
return (read_attribute(:end_at) - date).to_i rescue 14
end
def availability_time=(val)
date = created_at.nil? ? Date.current.to_date : created_at.to_date
write_attribute(:end_at, date+val.to_i.days)
end
def highlighted?
self.rank >= 4.75
end
def publish!
self.published = true
save
spawn do
tags = [localization.name, category.name, "praca", JOB_TYPE[self.type_id]]
tags << framework.name unless framework.nil?
tags << language.name unless language.nil?
- MicroFeed.send :streams => :all,
+ MicroFeed.send( :streams => :all,
:msg => "[#{company_name}] - #{title}",
:tags => tags,
- :link => seo_job_url(self, :host => "webpraca.net") if Rails.env == "production"
+ :link => seo_job_url(self, :host => "webpraca.net")) if Rails.env == "production"
end
end
def visited_by(ip)
visit = visits.find_or_create_by_ip(IPAddr.new(ip).to_i)
visits_count += 1 if visit.new_record?
save
end
def to_param
permalink
end
end
diff --git a/app/stylesheets/ui.less b/app/stylesheets/ui.less
index 7bc1440..7d654a3 100644
--- a/app/stylesheets/ui.less
+++ b/app/stylesheets/ui.less
@@ -1,602 +1,602 @@
/* Defaults */
@text_color: #393733;
@link_color: #31627E;
@hover_color: #FF5917;
/* Global */
body {
margin: 0;
padding: 0;
font: 12px Arial;
color: @text_color;
overflow: auto;
background: #76787B url('/images/bkg.png') repeat-x top;
}
h1, h2, h3, h4 { margin: 0 0 5px 0; }
a { color: @link_color; cursor: pointer; outline: none !important; text-decoration: none; }
a:hover, a:focus { color: @hover_color; }
a img { border: 0; }
/* Table */
table { border-collapse: collapse; width: 100%; }
td, th {
font-size:11px;
border-bottom:1px solid #eee;
padding:5px;
}
th { text-align:left; font-size:12px; }
thead th { font-weight:bold; color:#666; padding:2px 5px; font-size:11px; background:#e1e1e1 url(/images/nav-bg.gif) top left repeat-x; border-left:1px solid #ddd; border-bottom:1px solid #ddd; }
thead th:first-child { border-left:none !important; }
thead th.optional { font-weight:normal !important; }
tr.alt { background:#f6f6f6; }
/* IDS */
.prices input[type="text"] { width: 50px !important; text-align: right; }
#job_captcha_image, #applicant_captcha_image, .captcha img { margin-bottom: -22px !important; margin-right: 10px !important; }
#job_captcha_solution, #applicant_captcha_solution, .captcha input { width: 200px !important; }
#AdTaily_Widget_Container { padding-top: 5px; }
/* Custom class */
.rounded_corners (@radius: 5px) {
-moz-border-radius: @radius;
-webkit-border-radius: @radius;
border-radius: @radius;
-o-border-radius: @radius;
}
.rounded_corner_top_left(@radius: 5px) { -moz-border-radius-topleft: @radius; -webkit-border-top-left-radius: @radius; border-top-left-radius: @radius; }
.rounded_corner_top_right(@radius: 5px) { -moz-border-radius-topright: @radius; -webkit-border-top-right-radius: @radius; border-top-right-radius: @radius; }
.rounded_corner_bottom_left(@radius: 5px) { -moz-border-radius-bottomleft: @radius; -webkit-border-bottom-left-radius: @radius; border-bottom-left-radius: @radius; }
.rounded_corner_bottom_right(@radius: 5px) { -moz-border-radius-bottomright: @radius; -webkit-border-bottom-right-radius: @radius; border-bottom-right-radius: @radius; }
.reset { margin: 0; padding: 0; list-style: none; }
.text_center { text-align: center; }
.text_right { text-align: right; }
.clear { clear: both; }
.info { text-align: center; color: #ddd; font-size: 28px; font-weight: bold; }
.loader { background: transparent url('/images/ajax.gif') no-repeat center center; height: 20px; display: none; }
.right { float: right; }
.left { float: left; }
/* Flash */
.flash {
background-color: #A4E1A2;
border: 1px solid #DDE3D7;
text-shadow: #C0FDE3 0px 1px 0px;
.rounded_corners(5px);
color: #094808;
margin-top: 10px;
opacity: 0.8;
padding: 10px;
}
.flash.error {
background-color: #AF2B2B;
color: #fff;
border: 1px solid #DA3536;
text-shadow: #000 0px 1px 0px;
}
.flash:hover { opacity: 1.0; }
.flash .dismiss {
background: transparent url('/images/close.png') no-repeat !important;
float: right;
height: 10px;
width: 9px;
text-indent: 9999px;
overflow: hidden;
}
.flash p {
font-weight: normal;
line-height: 15px;
margin: 0px;
}
.flash_error {
background: #AF2B2B url('../images/icon-error.png') 20px center no-repeat;
color: #fff;
border: 1px solid #DA3536;
text-shadow: #000 0px 1px 0px;
}
/* Buttons */
.buttons { margin: 0 5px; }
.button {
background: #DDD url('../images/button.png') repeat-x 0px 0px;
border: 1px solid #999;
display: inline-block;
outline: none;
-webkit-box-shadow: rgba(0, 0, 0, 0.117188) 0px 1px 0px;
}
.button > input[type="button"], .button > input[type="submit"], .button > a {
border: none;
line-height: 23px;
height: 23px;
padding: 0 10px;
color: #333 !important;
font-weight: bold;
text-decoration: none;
font-size: 11px;
cursor: default;
background: transparent;
}
.button:active {
background-color: #ddd;
background-image: none;
}
.button img {
margin-bottom: -4px;
margin-right: 5px;
width: 16px;
height: 16px;
}
.button.right { float: right; }
/* TextFields */
select { min-width: 150px; }
input[type="text"], input[type="password"], textarea {
padding: 4px 3px !important;
border: 1px solid #96A6C5;
color: #000;
}
textarea { height: 200px; min-height: 200px; }
input[type="text"]:focus, input[type="password"]:focus, textarea:focus {
background-color: #e6f7ff;
border-bottom: 1px solid #7FAEFF;
border-right: 1px solid #7FAEFF;
border-left: 1px solid #4478A8;
border-top: 1px solid #4478A8;
}
form > fieldset {
border: 2px solid #ddd !important;
.rounded_corners;
padding: 10px 15px !important;
margin: 10px 5px !important;
}
form > fieldset > legend {
font-weight: bold;
padding: 0 15px 0px 0 !important;
margin-left: -22px !important;
background: #fff;
font-size: 16px;
color: #333 !important;
}
/* Wrapper */
@wrapper_width: 900px;
.wrapper {
margin: 0px auto;
width: @wrapper_width;
min-height: 500px;
}
/* Header */
@header_height: 80px;
.wrapper > .header {
height: @header_height;
width: @wrapper_width;
position:relative;
}
@logo_width: 347px;
@menu_color: #35373A;
@header_link_color: #D8D8D9;
.header > h1#logo {
left: 8px;
position: absolute;
top: 10px;
width: @logo_width;
}
.header > h1#logo a { color: #fff; font: 28px "Trebuchet MS"; font-weight: bold; }
.header > h1#logo a:hover { background: transparent; }
.header > ul.categories {
.reset;
position: absolute;
bottom: 5px;
left: 0px;
width: @content_width;
}
.header > ul.categories li {
display:inline;
margin-left: 3px;
}
.header > ul.categories li.right { float: right; margin-left: 6px; }
.header > ul.categories li > a {
padding: 5px 10px;
margin-top: 5px;
font-size: 13px;
color: @header_link_color;
.rounded_corner_top_left;
.rounded_corner_top_right;
background: @menu_color;
}
.header > ul.categories li > a:hover { background: #5d5f62; }
.header > ul.categories li > .selected { color: #fff; background: #2A2B2D !important; }
.header > ul.menu {
.reset;
.rounded_corner_bottom_left;
.rounded_corner_bottom_right;
position:absolute;
top: 0px;
padding: 5px 10px;
right: 0px;
background: @menu_color;
}
.header > ul.menu li{
display:inline;
margin-left: 3px;
padding-left: 6px;
border-left: 1px dotted #212326;
background-color:transparent;
font-size: 10px;
font-weight: bold;
color: @header_link_color;
}
.header > ul.menu li a { color: @header_link_color; }
.header > ul.menu li a:hover { color: #fff; background: transparent; }
.header > ul.menu li:first-child { border: 0; margin-left: 0; padding-left: 0; }
/* Sidebar */
@sidebar_width: 200px;
.wrapper > .sidebar {
float: right;
width: @sidebar_width;
margin-top: 20px;
}
.wrapper > .sidebar ul { .reset; }
/* content */
@content_padding_right: 10px;
@content_width: @wrapper_width - @sidebar_width - @content_padding_right;
.wrapper > .content {
float: left;
width: @content_width;
padding-right: @content_padding_right;
margin-top: 20px;
}
/*.wrapper > .content p { margin: 0 0 10px 0; padding: 0;} */
/* Box */
.box {
margin-bottom: 10px;
padding: 6px;
background: #9C9C9C;
.rounded_corners(5px);
}
@box_div_border_radius: 4px;
.box > div {
background: #fff;
margin-bottom: 10px;
padding-bottom: 5px;
.rounded_corners(@box_div_border_radius);
}
.box > div > .text { margin: 10px; }
.box > div > .text p { margin: 10px 0; }
.box > div:last-child { margin-bottom: 0; }
@title_height: 39px;
@sidebar_title_height: 29px;
.box .title {
height: @title_height;
.rounded_corner_top_right(@box_div_border_radius);
.rounded_corner_top_left(@box_div_border_radius);
display: block;
background: #fff url('/images/title-header.png') repeat-x bottom;
border-bottom: 1px solid #F1EFBD;
}
.box .title > h2, .box .title > h3 {
margin: 0;
padding: 1px 10px 0 10px;
line-height: @title_height - 1px;
font-weight: normal;
font-size: 18px;
color: #656666;
}
.box .title > h3 {
font-size: 16px;
line-height: @sidebar_title_height - 1px;
}
.box .title > h2 > span, .box .title > h3 > span { color: #8E8F8F; }
.box > div form { margin: 5px !important; }
.box p {
margin: 10px;
}
.sidebar .box .title, .box .title.mini {
height: @sidebar_title_height;
}
/* list */
.list {
.reset;
.clear;
}
-.list > li { clear: both; padding: 5px; }
+.list > li { clear: both; padding: 5px; min-height: 14px; }
.list > .alt { background:#f6f6f6; }
.list > li > .ranked { font-weight: bold; }
.list > li .handle { cursor: move; margin: 3px 5px 0 5px; }
.list > li > .badge {
float: right;
min-width: 18px;
padding: 2px 3px;
font-weight: bold;
font-size: 10px;
color: #fff;
background: #8798BB;
.rounded_corners(7px);
text-align: center;
}
.list > li > .rank {
.rounded_corners(2px);
text-align: center;
min-width: 18px;
padding: 2px 3px;
font-weight: bold;
font-size: 9px;
float: right;
background: #FFFF98;
border: 1px solid #E2E28C;
margin-top: -1px;
}
.list > li > .date {
font-size: 11px;
font-style: italic;
color: #7C7C7C;
}
/* more button */
.more {
background: #fff url('/images/more.gif') 0% 0% repeat-x;
border: 1px solid #DDD;
border-bottom: 1px solid #AAA;
border-right: 1px solid #AAA;
display: block;
font-size: 14px;
font-weight: bold;
color: inherit;
height: 22px;
line-height: 1.5em;
padding: 6px 0px;
text-align: center;
text-shadow: #fff 1px 1px 1px;
.rounded_corners(6px);
}
.more:hover {
background-position: 0% -78px;
border: 1px solid #BBB;
color: inherit;
}
.more:active {
background-position: 0% -38px;
color: #666;
}
/* Etykiety */
.etykieta {
display: block;
float: left;
font-size: 9px;
margin-right: 5px;
margin-top: -1px;
text-align: center;
width: 60px;
.rounded_corners(2px);
padding: 2px 3px;
color: #fff;
}
.etykieta:hover { color: #fff; }
.etykieta.remote {
background: #357CCB;
border: 1px solid #2C6AB0;
}
.etykieta.freelance {
background: #F8854E;
border: 1px solid #D27244;
}
.etykieta.full_time {
background: #408000;
border: 1px solid #366E01;
}
.etykieta.practice {
background: #FF6;
border: 1px solid #E2E25C;
color: #31627E;
}
.praktyka:hover { color: #31627E; }
.etykieta.free {
background: #D6D6D6;
border: 1px solid #B1B1B1;
color: #31627E;
}
.wolontariat:hover { color: #31627E; }
/* Pagination */
.pagination { background: white; margin: 5px 5px 0 5px; }
.pagination a, .pagination span {
padding: .2em .5em;
display: block;
float: left;
margin-right: 1px;
}
.pagination span.disabled {
color: #999;
border: 1px solid #DDD;
}
.pagination span.current {
font-weight: bold;
background: #2E6AB1;
color: white;
border: 1px solid #2E6AB1;
}
.pagination a {
text-decoration: none;
color: #105CB6;
border: 1px solid #9AAFE5;
}
.pagination a:hover, .pagination a:focus {
color: #003;
border-color: #003;
background-color: transparent;
}
.pagination .page_info {
background: #2E6AB1;
color: white;
padding: .4em .6em;
width: 22em;
margin-bottom: .3em;
text-align: center;
}
.pagination .page_info b {
color: #003;
background: #6aa6ed;
padding: .1em .25em;
}
.pagination:after {
content: ".";
display: block;
height: 0;
clear: both;
visibility: hidden;
}
* html .pagination { height: 1%; }
*:first-child+html .pagination { overflow: hidden; }
/* describe list */
@dt_width: 180px;
@dt_padding_right: 10px;
@dl_padding_left: 10px;
dl {
padding: 0px;
margin: 10px 0 0 0;
display: block;
}
dl dt {
width: @dt_width;
text-align: right;
color: #888;
float: left;
display: block;
padding: 0 @dt_padding_right 6px 0;
margin: 0;
}
dl dd {
width: @content_width - @dt_width - @dt_padding_right - @dl_padding_left - 15px;
border-left: 1px solid #ccc;
float: left;
padding: 0 0 10px @dl_padding_left;
margin: 0;
}
dl dd:last-child { padding-bottom: 0px; }
dl dd ul {
padding: 5px 0 0 20px;
margin: 0;
}
/* feed icon */
.feed {
float: right;
margin-top: 5px;
margin-right: -3px;
}
/* footer */
.footer {
margin: 10px auto;
width: @wrapper_width;
color: #D8D8D9;
}
.footer strong a { color: #fff; }
.footer a { color: #D8D8D9; }
.footer a:hover { color: #fff; }
.footer .right { margin-top: 3px; }
\ No newline at end of file
diff --git a/app/views/applicants/new.html.erb b/app/views/applicants/new.html.erb
index e5061d7..2be5fc8 100644
--- a/app/views/applicants/new.html.erb
+++ b/app/views/applicants/new.html.erb
@@ -1,35 +1,35 @@
<div class="box">
<div>
<div class="title">
- <h2><span>Aplikuj</span> online</h2>
+ <h2><%= t('applicant.title') %></h2>
</div>
<% semantic_form_for [@job, @applicant], :html => { :multipart => true } do |f| %>
<%#= f.error_messages %>
- <% f.inputs :name => "TreÅÄ aplikacji" do %>
+ <% f.inputs :name => t('applicant.fieldset') do %>
<li class="text">
<label>Do:</label>
<%= link_to @job.company_name, @job.website, :target => "_blank" %>
</li>
<%= f.input :email %>
- <%= f.input :body, :hint => "wiadomoÅÄ lub list motywacyjny" %>
- <%= f.input :cv, :required => false, :hint => "Max. 5 MB. Rekomendowane formaty: PDF, DOC, TXT, RTF, ZIP, RAR." %>
+ <%= f.input :body %>
+ <%= f.input :cv, :required => false %>
<li class="string required">
- <%= f.label :captcha, 'Kod z obrazka*' %>
+ <%= f.label :captcha, t('formtastic.labels.job.captcha') %>
<%= f.captcha_challenge %>
<%= f.captcha_field %>
<%= inline_errors @applicant, :captcha_solution %>
</li>
<% end %>
<div class="buttons">
<div class="button">
<%= f.submit "WyÅlij" %>
</div>
albo <%= link_to "anuluj", @job %>
</div>
<% end %>
</div>
</div>
diff --git a/app/views/contact/new.html.erb b/app/views/contact/new.html.erb
index cdd9f4e..004226d 100644
--- a/app/views/contact/new.html.erb
+++ b/app/views/contact/new.html.erb
@@ -1,38 +1,38 @@
<div class="box">
<div>
<div class="title">
- <h2><%= title @contact_handler.job.nil? ? "Kontakt" : "Kontakt z #{@contact_handler.job.company_name}" %></h2>
+ <h2><%= title @contact_handler.job.nil? ? t('contact.title') : "#{t('contact.title')} #{@contact_handler.job.company_name}" %></h2>
</div>
- <%= content_tag :p, "BÄdziemy wdziÄczni za wszelkie uwagi dotyczÄ
ce funkcjonowania serwisu. " if @contact_handler.job.nil? %>
+ <%= content_tag :p, t('contact.description') if @contact_handler.job.nil? %>
<% semantic_form_for(@contact_handler, :url => contact_url) do |f| %>
<% f.inputs do %>
<% unless @contact_handler.job.nil? %>
<li class="text">
- <label>Do:</label>
+ <label><%= t('contact.recipient') %></label>
<%= link_to @contact_handler.job.company_name, @contact_handler.job.website, :target => "_blank" %>
</li>
<% end %>
<%= f.hidden_field :job_id %>
<%= f.input :email %>
- <%= f.input :subject, :label => "Temat" %>
- <%= f.input :body, :as => :text, :label => "TreÅÄ" %>
+ <%= f.input :subject, :label => t('contact.subject') %>
+ <%= f.input :body, :as => :text, :label => t('contact.body') %>
<% end %>
- <% f.inputs :name => "Czy jesteÅ czÅowiekiem" do %>
+ <% f.inputs :name => t('jobs.form.fieldset.human_test') do %>
<li class="string required captcha">
- <%= f.label :captcha, 'Kod z obrazka*' %>
+ <%= f.label :captcha, t('formtastic.labels.job.captcha') %>
<%= f.captcha_challenge %>
<%= f.captcha_field %>
<%= inline_errors @contact_handler, :captcha_solution %>
</li>
<% end %>
<div class="buttons">
<div class="button">
- <%= f.submit 'WyÅlij!' %>
+ <%= f.submit t('contact.submit') %>
</div>
</div>
<% end %>
</div>
</div>
diff --git a/app/views/contact_mailer/contact_notification.html.erb b/app/views/contact_mailer/contact_notification.html.erb
index e97f35d..7410c4e 100644
--- a/app/views/contact_mailer/contact_notification.html.erb
+++ b/app/views/contact_mailer/contact_notification.html.erb
@@ -1,6 +1,5 @@
Temat: <%= @contact_handler.subject %>
E-mail: <%= @contact_handler.email %>
<%= "Oferta: #{@contact_handler.job.title}" unless @contact_handler.job.nil? -%>
-
-TreÅÄ:
+
<%= @contact_handler.body %>
\ No newline at end of file
diff --git a/app/views/job_mailer/job_applicant.erb b/app/views/job_mailer/job_applicant.erb
index bbe4f46..674ed56 100644
--- a/app/views/job_mailer/job_applicant.erb
+++ b/app/views/job_mailer/job_applicant.erb
@@ -1,13 +1,12 @@
-Witaj <%= @job.company_name %>!,
+<%= t('mailer.job_posted.greetings') %> <%= @job.company_name %>!,
-PojawiÅa siÄ osoba zainteresowana twojÄ
ofertÄ
:
+<%= t('mailer.job_applicant.body') %>
<%= @job_path %>
-----------------------------------------------------------------------------------
E-Mail: <%= @applicant.email %>
-TreÅÄ:
<%= @applicant.body %>
-----------------------------------------------------------------------------------
<%- if @applicant.have_attachment? -%>
-ZaÅÄ
cznik: <%= @attachment_path %>
+<%= t('mailer.job_applicant.attachment') %>: <%= @attachment_path %>
<%- end -%>
\ No newline at end of file
diff --git a/app/views/jobs/_sidebar.html.erb b/app/views/jobs/_sidebar.html.erb
index 35e4267..46bf3d0 100644
--- a/app/views/jobs/_sidebar.html.erb
+++ b/app/views/jobs/_sidebar.html.erb
@@ -1,56 +1,57 @@
<div class="box">
<div>
<div class="title"><h3><%= t('layout.sidebar.type') %></h3></div>
<ul class="list">
<% Job.find_grouped_by_type.each do | type_id, jobs_count | %>
<li class="<%= cycle('normal', 'alt') %>">
<span class="badge"><%= jobs_count %></span>
<%= link_to t("jobs.type.#{JOB_TYPES[type_id]}"), job_type_path(JOB_TYPES[type_id]) , :class => "etykieta #{JOB_TYPES[type_id]}"%>
+ <span class="clear"></span>
</li>
<% end %>
</ul>
<div class="clear"></div>
</div>
<div>
<div class="title">
<h3><%= t('layout.sidebar.localization') %></h3>
</div>
<ul class="list">
<% for place in Localization.find_job_localizations %>
<li class="<%= cycle('normal', 'alt') %>">
<span class="badge"><%= place.jobs_count %></span>
<%= link_to place.name, localization_path(place.permalink) %>
</li>
<% end %>
</ul>
</div>
<div>
<div class="title">
<h3><%= t('layout.sidebar.language') %></h3>
</div>
<ul class="list">
<% for language in Language.find_job_languages %>
<li class="<%= cycle('normal', 'alt') %>">
<span class="badge"><%= language.jobs_count %></span>
<%= link_to language.name, language_path(language) %>
</li>
<% end %>
</ul>
</div>
<div>
<div class="title">
<h3><%= t('layout.sidebar.frameworks') %></h3>
</div>
<ul class="list">
<% for framework in Framework.find_job_frameworks %>
<li class="<%= cycle('normal', 'alt') %>">
<span class="badge"><%= framework.jobs_count %></span>
<%= link_to framework.name, framework_path(framework.permalink) %>
</li>
<% end %>
</ul>
</div>
</div>
diff --git a/app/views/jobs/search.html.erb b/app/views/jobs/search.html.erb
index ff20121..2c49529 100644
--- a/app/views/jobs/search.html.erb
+++ b/app/views/jobs/search.html.erb
@@ -1,43 +1,43 @@
<% content_for :sidebar do %>
<%= render :partial => "/jobs/sidebar" %>
<% end %>
<% unless (@jobs.nil? || @jobs.empty?) %>
<div class="box">
<div>
<div class="title">
<h2>
<%= link_to image_tag('feed.png'), search_jobs_url(stripped_params(:format => :rss)), :title => "Subskrybuj wyszukiwanie", :class => "feed" %>
- Wyniki dla <span>wyszukiwania</span>
+ <%= t('title.finded_jobs') %>
</h2>
</div>
<%= render :partial => "jobs", :object => @jobs %>
</div>
</div>
<% end %>
<div class="box">
<div>
<div class="title">
- <h2><span>Szukaj</span> oferty</h2>
+ <h2><%= t('title.search') %></h2>
</div>
<% semantic_form_for @search, :url => search_jobs_path, :html => { :method => :post } do |f| %>
- <% f.inputs :name => "Wyszukiwarka" do %>
- <%= f.input :has_text, :required => false, :label => "ZawierajÄ
cy tekst" %>
- <%= f.input :category_id_equals, :required => false, :as => :check_boxes, :collection => Category.all.map { |category| [category.name, category.id] }, :wrapper_html => { :class => "columns" }, :label => "Kategorie" %>
- <%= f.input :type_id_equals, :required => false, :as => :check_boxes, :collection => collection_from_types(JOB_TYPES), :label => "Typ" %>
- <%= f.input :localization_id_equals, :required => false, :as => :check_boxes, :collection => Localization.all.map { |l| [l.name, l.id] }, :wrapper_html => { :class => "columns" }, :label => "Lokalizacja" %>
- <%= f.input :framework_id_equals, :required => false, :as => :check_boxes, :collection => Framework.all.map { |frame| [frame.name, frame.id] }, :wrapper_html => { :class => "columns" }, :label => "Używane frameworki" %>
+ <% f.inputs :name => t('formtastic.labels.search.fieldset') do %>
+ <%= f.input :has_text, :required => false, :label => t('formtastic.labels.search.has_text') %>
+ <%= f.input :category_id_equals, :required => false, :as => :check_boxes, :collection => Category.all.map { |category| [category.name, category.id] }, :wrapper_html => { :class => "columns" }, :label => t('formtastic.labels.search.categories') %>
+ <%= f.input :type_id_equals, :required => false, :as => :check_boxes, :collection => JOB_TYPES.enum_for(:each_with_index).map { |type, index| [t("jobs.type.#{type}"), index] }, :label => t('formtastic.labels.search.type') %>
+ <%= f.input :localization_id_equals, :required => false, :as => :check_boxes, :collection => Localization.all.map { |l| [l.name, l.id] }, :wrapper_html => { :class => "columns" }, :label => t('formtastic.labels.search.localizations') %>
+ <%= f.input :framework_id_equals, :required => false, :as => :check_boxes, :collection => Framework.all.map { |frame| [frame.name, frame.id] }, :wrapper_html => { :class => "columns" }, :label => t('formtastic.labels.search.frameworks') %>
<li class="numeric prices">
- <label>WideÅki zarobkowe:</label>
- <%= f.text_field :price_from_greater_than_or_equal_to %> do <%= f.text_field :price_to_less_than_or_equal_to %> PLN
+ <label><%= t('formtastic.labels.search.pay_band') %></label>
+ <%= f.text_field :price_from_greater_than_or_equal_to %> do <%= f.text_field :price_to_less_than_or_equal_to %> <%= t('number.currency.format.unit') %>
</li>
<% end %>
<div class="buttons">
- <div class="button"><%= f.submit "Szukaj!" %></div>
+ <div class="button"><%= f.submit t('formtastic.labels.search.submit') %></div>
</div>
<% end %>
</div>
</div>
diff --git a/app/views/layouts/application.html.erb b/app/views/layouts/application.html.erb
index 87c1a2a..de9f0b3 100644
--- a/app/views/layouts/application.html.erb
+++ b/app/views/layouts/application.html.erb
@@ -1,91 +1,79 @@
<!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" lang="pl">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
- <meta name="google-site-verification" content="zE20xzrx6CCNbFsmsNTok9xaPavS0Cmu7hJxdUbNqN8" />
<%= display_meta_tags :site => WebSiteConfig['website']['name'] %>
<meta name="viewport" content="width=900" />
<%= rss_link("RSS", jobs_url(:format => :rss)) %>
<%= rss_link("ATOM", jobs_url(:format => :atom)) %>
<%= javascript_tag "window._token = '#{form_authenticity_token}'" %>
<%= javascript_include_merged :base %>
<%= stylesheet_link_merged :base %>
</head>
<body>
<div class="wrapper">
<div class="header">
<h1 id="logo"><%= link_to WebSiteConfig['website']['name'], root_path %></h1>
<ul class="categories">
<li class="right">
- <%= link_to t('layout.popular'), seo_jobs_path(:order => 'najpopularniejsze', :category => params[:category]), :class => (!@order.nil? && @order == :rank) ? "selected" : "normal" %>
+ <%= link_to t('layout.popular'), seo_jobs_path(:order => 'popular', :category => params[:category]), :class => (!@order.nil? && @order == :rank) ? "selected" : "normal" %>
</li>
<li class="right">
- <%= link_to t('layout.latest'), seo_jobs_path(:order => 'najnowsze', :category => params[:category] ), :class => (!@order.nil? && @order == :created_at) ? "selected" : "normal" %>
+ <%= link_to t('layout.latest'), seo_jobs_path(:order => 'latest', :category => params[:category] ), :class => (!@order.nil? && @order == :created_at) ? "selected" : "normal" %>
</li>
<% for category in Category.all(:order => "position") %>
<li>
<%= link_to category.name, seo_jobs_path(:order => params[:order], :category => category.permalink), :class => (!@category.nil? && @category.id == category.id) ? "selected" : "normal" %>
</li>
<% end %>
</ul>
<ul class="menu">
<li><%= link_to t('layout.menu.main'), root_path %></li>
<li><%= link_to t('layout.menu.search'), search_jobs_path %></li>
- <li><%= link_to t('layout.menu.about'), "/strona/informacje/" %></li>
- <li><%= link_to t('layout.menu.terms'), "/strona/regulamin/" %></li>
- <li><%= link_to t('layout.menu.follow'), "/strona/obserwuj-nas" %></li>
+ <li><%= link_to t('layout.menu.about'), "/page/informacje/" %></li>
+ <li><%= link_to t('layout.menu.terms'), "/page/regulamin/" %></li>
+ <li><%= link_to t('layout.menu.follow'), "/page/obserwuj-nas" %></li>
<li><%= link_to t('layout.menu.contact'), contact_path %></li>
</ul>
</div>
<%- flash.each do |name, msg| -%>
<div class="<%= "flash #{name}" %>">
<a href="#" class="dismiss">X</a>
<p><%= msg %></p>
</div>
<%- end -%>
<div class="sidebar">
<div class="box">
<%= link_to t('layout.sidebar.post_job'), new_job_path, :id => "add_job", :class => "more", :rel => "nofollow" %>
</div>
<%= yield :sidebar %>
<% if @ads_pos == :right %>
<div class="box">
<div>
<%= render :partial => "/shared/ads" %>
</div>
</div>
<% end %>
</div>
<div class="content">
<%= yield %>
<% if @ads_pos == :bottom %>
<div class="box">
<div>
<%= render :partial => "/shared/ads" %>
</div>
</div>
<% end %>
</div>
<div class="clear"></div>
</div>
<%= render :partial => "/shared/footer" %>
- <script type="text/javascript" src="http://flaker.pl/track/site/1122612"></script>
- <script type="text/javascript" src="http://app.sugester.pl/webpraca/widget.js"></script>
- <script type="text/javascript">
- var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
- document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
- </script>
- <script type="text/javascript">
- try {
- var pageTracker = _gat._getTracker("UA-11469054-5");
- pageTracker._trackPageview();
- } catch(err) {}</script>
</body>
</html>
\ No newline at end of file
diff --git a/app/views/shared/error_404.html.erb b/app/views/shared/error_404.html.erb
index ae28798..27879b8 100644
--- a/app/views/shared/error_404.html.erb
+++ b/app/views/shared/error_404.html.erb
@@ -1,10 +1,10 @@
<div class="box">
<div>
<div class="title">
- <h2>Nie znaleziono strony!</h2>
+ <h2><%= t('404.title') %></h2>
</div>
<div class="text_center">
<img src="/images/404.jpeg" width="440" height="358" alt="404" />
</div>
</div>
</div>
diff --git a/app/views/shared/error_500.html.erb b/app/views/shared/error_500.html.erb
index 5c3d55e..c16fd77 100644
--- a/app/views/shared/error_500.html.erb
+++ b/app/views/shared/error_500.html.erb
@@ -1,11 +1,11 @@
<div class="box">
<div>
<div class="title">
- <h2>CoÅ poszÅo nie tak... Aplikacja trafiÅa na nieobsÅugiwany wyjÄ
tek.</h2>
+ <h2><%= t('500.title') %></h2>
</div>
<div class="text_center">
<img src="/images/500.jpeg" width="500" height="416" alt="500" />
</div>
</div>
</div>
diff --git a/config/deploy.rb b/config/deploy.rb
new file mode 100644
index 0000000..ccba667
--- /dev/null
+++ b/config/deploy.rb
@@ -0,0 +1,82 @@
+set :application, "webpraca"
+set :repository, "git://github.com/macbury/webpraca.git"
+set :scm, :git
+
+set :branch, "master"
+set :user, "webpraca"
+set :deploy_to, "/home/webpraca/www/apps/#{application}"
+set :rails_env, "production"
+set :use_sudo, false
+
+role :app, "webpraca.megiteam.pl"
+role :web, "webpraca.megiteam.pl"
+role :db, "webpraca.megiteam.pl", :primary => true
+
+after "deploy:symlink", "deploy:symlink_uploaded"
+after "deploy:symlink", "deploy:install_gems"
+after "deploy:symlink", "deploy:rebuild_assets"
+after "deploy:symlink", "deploy:update_crontab"
+after "deploy:symlink", "deploy:copy_old_sitemap"
+
+namespace :deploy do
+ desc "Restart aplikacji przy pomocy skryptu Megiteam"
+
+ task :restart, :role => :app do
+ run "cd #{deploy_to}/current; restart-app webpraca"
+ run "cd #{deploy_to}/current; echo RAILS_ENV='production' > .environment"
+ end
+
+ desc "start"
+ task :start, :role => :app do
+ run "restart-app #{ application }"
+ end
+
+ desc "stop"
+ task :stop, :role => :app do
+ run "restart-app #{ application }"
+ end
+
+ desc "Stworz symlinki do wspoldzielonych plikow"
+ task :symlink_uploaded, :roles => :app do
+
+ run "ln -nfs #{shared_path}/config/mailer.yml #{current_path}/config/mailer.yml"
+ run "ln -nfs #{shared_path}/config/exception_notifier.yml #{current_path}/config/exception_notifier.yml"
+ run "ln -nfs #{shared_path}/config/website_config.yml #{current_path}/config/website_config.yml"
+ run "ln -nfs #{shared_path}/config/micro_feed.yml #{current_path}/config/micro_feed.yml"
+ run "ln -nfs #{shared_path}/config/database.yml #{current_path}/config/database.yml"
+ run "ln -nfs #{shared_path}/config/newrelic.yml #{current_path}/config/newrelic.yml"
+ run "ln -nfs #{shared_path}/public/images/captchas #{current_path}/public/images/captchas"
+ run "ln -nfs #{shared_path}/tmp/attachments #{current_path}/tmp/attachments"
+ end
+
+
+ desc "Rebuild asset files"
+ task :rebuild_assets, :roles => :app do
+ run "cd #{ current_path } ; rake more:parse"
+ run "cd #{ current_path } ; rake asset:packager:delete_all"
+ run "cd #{ current_path } ; rake asset:packager:build_all"
+ end
+
+ task :copy_old_sitemap do
+ run "if [ -e #{previous_release}/public/sitemap_index.xml.gz ]; then cp #{previous_release}/public/sitemap* #{current_release}/public/; fi"
+ end
+
+ task :captchas, :roles => :app do
+ run "cd #{ current_path } ; rake validates_captcha:create_static_images COUNT=50"
+ end
+
+ desc "Install gems"
+ task :install_gems, :roles => :app do
+ run "cd #{ current_path } ; rake gems:install"
+ end
+
+ desc "Update the crontab file"
+ task :update_crontab, :roles => :db do
+ run "cd #{release_path} && whenever --update-crontab #{application}"
+ end
+
+ task :publish, :roles => :db do
+ run "cd #{release_path} && rake webpraca:jobs:publish RAILS_ENV=production"
+
+ end
+end
diff --git a/config/environment.rb b/config/environment.rb
index d7942ae..5c4baae 100644
--- a/config/environment.rb
+++ b/config/environment.rb
@@ -1,51 +1,51 @@
# Be sure to restart your server when you modify this file
# Specifies gem version of Rails to use when vendor/rails is not present
# Bootstrap the Rails environment, frameworks, and default configuration
require File.join(File.dirname(__FILE__), 'boot')
Rails::Initializer.run do |config|
config.gem 'sitemap_generator', :lib => false, :source => 'http://gemcutter.org'
config.gem 'less', :source => 'http://gemcutter.org', :lib => false
config.gem 'meta-tags', :lib => 'meta_tags', :source => 'http://gemcutter.org'
config.gem 'declarative_authorization'
config.gem 'searchlogic'
config.gem 'RedCloth', :lib => "redcloth"
config.gem 'authlogic'
config.gem 'whenever', :lib => false, :source => 'http://gemcutter.org/'
config.gem 'highline', :lib => false
config.gem "factory_girl", :lib => false
config.gem "faker", :lib => false
config.gem 'rspec', :lib => false, :version => '>=1.2.9'
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Add additional load paths for your own custom dirs
# config.load_paths += %W( #{RAILS_ROOT}/extras )
# Specify gems that this application depends on and have them installed with rake gems:install
# config.gem "bj"
# config.gem "hpricot", :version => '0.6', :source => "http://code.whytheluckystiff.net"
# config.gem "sqlite3-ruby", :lib => "sqlite3"
# config.gem "aws-s3", :lib => "aws/s3"
# Only load the plugins named here, in the order given (default is alphabetical).
# :all can be used as a placeholder for all plugins not explicitly named
#config.plugins = [ :all, :less, 'less-rails' ]
# Skip frameworks you're not going to use. To use Rails without a database,
# you must remove the Active Record framework.
# config.frameworks -= [ :active_record, :active_resource, :action_mailer ]
# Activate observers that should always be running
# config.active_record.observers = :cacher, :garbage_collector, :forum_observer
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names.
config.time_zone = 'Warsaw'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}')]
- config.i18n.default_locale = :pl
+ config.i18n.default_locale = :en
end
\ No newline at end of file
diff --git a/config/locales/en.yml b/config/locales/en.yml
index f265c06..9f92c0e 100644
--- a/config/locales/en.yml
+++ b/config/locales/en.yml
@@ -1,5 +1,192 @@
-# Sample localization file for English. Add more files in this directory for other locales.
-# See http://github.com/svenfuchs/rails-i18n/tree/master/rails%2Flocale for starting points.
+# Polish translations for Ruby on Rails
+# by Jacek Becela (jacek.becela@gmail.com, http://github.com/ncr)
en:
- hello: "Hello world"
\ No newline at end of file
+ 500:
+ title: "CoÅ poszÅo nie tak... Aplikacja trafiÅa na nieobsÅugiwany wyjÄ
tek."
+ 404:
+ title: "Nie znaleziono strony!"
+ applicant:
+ title: "Aplikuj online"
+ fieldset: "TreÅÄ aplikacji"
+ contact:
+ title: "Kontakt"
+ description: "BÄdziemy wdziÄczni za wszelkie uwagi dotyczÄ
ce funkcjonowania serwisu."
+ recipient: "Od"
+ subject: "Temat"
+ body: "TreÅÄ"
+ submit: "WyÅlij!"
+ mailer:
+ job_applicant:
+ body: "PojawiÅa siÄ osoba zainteresowana twojÄ
ofertÄ
: "
+ attachment: "ZaÅÄ
cznik"
+ job_posted:
+ greetings: "Witaj"
+ publish: "Aby opublikowaÄ swojÄ
ofertÄ kliknij na link poniżej"
+ path_to_job: "Twoja oferta zostaÅa dodana i znajduje siÄ poda adresem:"
+ path_to_edit_job: "Jeżeli chcesz wprowadziÄ zmiany w ofercie kliknij na link poniżej"
+ path_to_destroy_job: "Aby usunÄ
Ä ofertÄ kliknij na poniższy link"
+ formtastic:
+ labels:
+ search:
+ fieldset: "Wyszukiwarka"
+ categories: "Kategorie"
+ has_text: "ZawierajÄ
cy tekst"
+ type: "Typ"
+ localizations: "Lokalizacja"
+ frameworks: "Używane frameworki"
+ pay_band: "WideÅki zarobkowe"
+ submit: "Szukaj!"
+ websiteconfig:
+ groups:
+ website: "Strona WWW"
+ js: "Skrypty"
+ js:
+ google_analytics: "Google Analytics"
+ widget: "Reklama"
+ website:
+ name: "Nazwa"
+ tags: "SÅowa kluczowe"
+ description: "Opis"
+ applicant:
+ email: "Twój E-Mail"
+ body: "TreÅÄ"
+ cv: "Dodaj ofertÄ/CV"
+ job:
+ title: "TytuÅ"
+ place_id: "Lokalizacja"
+ description: "Opis"
+ availability_time: "DÅugoÅÄ trwania"
+ remote_job: "Praca zdalna"
+ type_id: "Typ"
+ category_id: "Kategoria"
+ company_name: "Nazwa"
+ website: "Strona WWW"
+ framework_name: "Framework"
+ localization_id: "Lokalizacja"
+ apply_online: "Aplikuj online"
+ email_title: "TytuÅ emaila"
+ language: "JÄzyk"
+ pay_band: "WideÅki zarobkowe"
+ pay_band_detail: "PLN na miesiÄ
c, netto"
+ captcha: 'Kod z obrazka*'
+ user:
+ password: "HasÅo"
+ password_confirmation: "Powtórz hasÅo"
+ hints:
+ applicant:
+ body: "wiadomoÅÄ lub list motywacyjny"
+ cv: "Max. 5 MB. Rekomendowane formaty: PDF, DOC, TXT, RTF, ZIP, RAR."
+ job:
+ availability_time: "ile dni oferta ma byÄ ważna(od 1 do 60 dni)"
+ localization_id: "np. 'Warszawa', 'Kraków, UK'"
+ framework_id: "gÅówny framework którego znajomoÅÄ jest wymagana, podaj peÅnÄ
nazwÄ"
+ apply_online: "uaktywnia formularz umożliwiajÄ
cy przesyÅanie aplikacji online w ofercie"
+ email_title: "np. MÅodszy programista, Ruby Developer/18/12/71 itp"
+ email: "Pod wskazany adres zostanÄ
przesÅane linki do edycji oferty, nie bÄdzie on widoczny publicznie(zamiast niego bÄdzie dostÄpny formularz kontaktowy)."
+ website: "http://"
+ flash:
+ error:
+ access_denied: "Access denied"
+ notice:
+ email_verification: "On your email was verification email!"
+ job_updated: "Your job was successfully updated!"
+ job_published: "Your job was successfully published!"
+ job_deleted: "Job was deleted!"
+ contact_sended: "Thank you!"
+ application_sended: "Your application was sended!"
+ title:
+ popular: "popular jobs"
+ latest: "latest jobs"
+ search: "Search Job"
+ finded_jobs: "Finded Jobs"
+ jobs: "Jobs"
+ admin: "Admin panel"
+ jobs:
+ empty: "Empty"
+ show:
+ type: "Type"
+ category: "Category"
+ rank: "Rank"
+ employer: "Employer"
+ localization: "Localization"
+ framework: "Framework"
+ language: "Language"
+ pay_band: "Pay Band"
+ contact: "Contact"
+ published_at: "Posted"
+ end_at: "End at"
+ visited: "Visited"
+ description: "Description"
+ apply_online: "Apply online!"
+ form:
+ new:
+ title: "Post Job"
+ submit: "I agree with Terms and I want post job"
+ cancel: "cancel"
+ edit:
+ title: "Edit job"
+ submit: "Save changes"
+ destroy: "delete"
+ destroy_confirm: "Are you sure?"
+ fieldset:
+ job_details: "Details"
+ apply_online: "Apply on-line!"
+ company_details: "Company info"
+ human_test: "Are you human?"
+ type:
+ full_time: "Full-Time"
+ freelance: "freelance"
+ free: "free"
+ practice: "practice"
+ remote: "remote"
+ type_long:
+ full_time: "Full time job"
+ freelance: "freelance"
+ free: "free"
+ practice: "practice"
+ layout:
+ popular: "Popular"
+ latest: "Latest"
+ menu:
+ main: "Home"
+ search: "Search"
+ about: "About"
+ terms: "Terms"
+ follow: "Follow us"
+ contact: "Contact"
+ sidebar:
+ post_job: "Post Job for FREE!"
+ type: "type"
+ localization: "localization"
+ language: "language"
+ frameworks: "framework"
+ home:
+ title: "latest jobs from IT"
+ popular: "Popular"
+ latest: "Latest"
+ jobs: "jobs"
+ more_jobs: "show more"
+
+ datetime:
+ distance_in_words:
+ ago: "ago"
+
+ activerecord:
+ models:
+ user: "User"
+ job: "Job"
+ search: "Search"
+ applicant: "Applicant"
+ comment:
+ attributes:
+ captcha_solution:
+ blank: 'must be presented'
+ invalid: 'invalid input'
+
+ support:
+ array:
+ last_word_connector: " and "
+ for_word_connector: " for "
+ in_word_connector: " in "
+ or_word_connector: " or "
diff --git a/config/locales/pl.yml b/config/locales/pl.yml
index df5a5dd..d6dac4b 100644
--- a/config/locales/pl.yml
+++ b/config/locales/pl.yml
@@ -1,278 +1,312 @@
# Polish translations for Ruby on Rails
# by Jacek Becela (jacek.becela@gmail.com, http://github.com/ncr)
pl:
+ 500:
+ title: "CoÅ poszÅo nie tak... Aplikacja trafiÅa na nieobsÅugiwany wyjÄ
tek."
+ 404:
+ title: "Nie znaleziono strony!"
+ applicant:
+ title: "Aplikuj online"
+ fieldset: "TreÅÄ aplikacji"
+ contact:
+ title: "Kontakt"
+ description: "BÄdziemy wdziÄczni za wszelkie uwagi dotyczÄ
ce funkcjonowania serwisu."
+ recipient: "Od"
+ subject: "Temat"
+ body: "TreÅÄ"
+ submit: "WyÅlij!"
mailer:
+ job_applicant:
+ body: "PojawiÅa siÄ osoba zainteresowana twojÄ
ofertÄ
: "
+ attachment: "ZaÅÄ
cznik"
job_posted:
greetings: "Witaj"
publish: "Aby opublikowaÄ swojÄ
ofertÄ kliknij na link poniżej"
path_to_job: "Twoja oferta zostaÅa dodana i znajduje siÄ poda adresem:"
path_to_edit_job: "Jeżeli chcesz wprowadziÄ zmiany w ofercie kliknij na link poniżej"
path_to_destroy_job: "Aby usunÄ
Ä ofertÄ kliknij na poniższy link"
formtastic:
labels:
+ search:
+ fieldset: "Wyszukiwarka"
+ categories: "Kategorie"
+ has_text: "ZawierajÄ
cy tekst"
+ type: "Typ"
+ localizations: "Lokalizacja"
+ frameworks: "Używane frameworki"
+ pay_band: "WideÅki zarobkowe"
+ submit: "Szukaj!"
websiteconfig:
groups:
website: "Strona WWW"
js: "Skrypty"
js:
google_analytics: "Google Analytics"
widget: "Reklama"
website:
name: "Nazwa"
tags: "SÅowa kluczowe"
description: "Opis"
applicant:
email: "Twój E-Mail"
body: "TreÅÄ"
cv: "Dodaj ofertÄ/CV"
job:
title: "TytuÅ"
place_id: "Lokalizacja"
description: "Opis"
availability_time: "DÅugoÅÄ trwania"
remote_job: "Praca zdalna"
type_id: "Typ"
category_id: "Kategoria"
company_name: "Nazwa"
website: "Strona WWW"
framework_name: "Framework"
localization_id: "Lokalizacja"
apply_online: "Aplikuj online"
email_title: "TytuÅ emaila"
language: "JÄzyk"
pay_band: "WideÅki zarobkowe"
pay_band_detail: "PLN na miesiÄ
c, netto"
captcha: 'Kod z obrazka*'
user:
password: "HasÅo"
password_confirmation: "Powtórz hasÅo"
hints:
+ applicant:
+ body: "wiadomoÅÄ lub list motywacyjny"
+ cv: "Max. 5 MB. Rekomendowane formaty: PDF, DOC, TXT, RTF, ZIP, RAR."
job:
availability_time: "ile dni oferta ma byÄ ważna(od 1 do 60 dni)"
localization_id: "np. 'Warszawa', 'Kraków, UK'"
framework_id: "gÅówny framework którego znajomoÅÄ jest wymagana, podaj peÅnÄ
nazwÄ"
apply_online: "uaktywnia formularz umożliwiajÄ
cy przesyÅanie aplikacji online w ofercie"
email_title: "np. MÅodszy programista, Ruby Developer/18/12/71 itp"
email: "Pod wskazany adres zostanÄ
przesÅane linki do edycji oferty, nie bÄdzie on widoczny publicznie(zamiast niego bÄdzie dostÄpny formularz kontaktowy)."
website: "zaczynajÄ
cy siÄ od http://"
flash:
+ error:
+ access_denied: "Nie masz wystarczajÄ
cych uprawnieÅ aby móc odwiedziÄ tÄ
stronÄ"
notice:
email_verification: "Na twój e-mail zostaÅ wysÅany link którym opublikujesz ofertÄ."
job_updated: "Zapisano zmiany w ofercie."
job_published: "Twoja oferta jest już widoczna!"
job_deleted: "Oferta zostaÅa usuniÄta"
+ contact_sended: "DziÄkujemy za wiadomoÅÄ!"
+ application_sended: "Twoja aplikacja zostaÅa wysÅana"
title:
popular: "najpopularniejsze oferty pracy IT"
latest: "najnowsze oferty pracy IT"
search: "Szukaj oferty"
finded_jobs: "Znalezione oferty"
jobs: "Oferty pracy IT"
+ admin: "Panel administracyjny"
jobs:
empty: "Brak ofert"
show:
type: "Typ"
category: "Kategoria"
rank: "Ocena"
employer: "Pracodawca"
- localization: "Localization"
+ localization: "Lokalizacje"
framework: "Framework"
language: "JÄzyk"
pay_band: "WideÅko zarobkowe"
contact: "Kontakt"
published_at: "Data rozpoczÄcia"
end_at: "Data zakoÅczenia"
visited: "WyÅwietlona"
description: "Opis oferty"
apply_online: "Aplikuj online!"
form:
new:
title: "Nowa oferta"
submit: "Zgadzam siÄ z regulaminem i chcÄ dodaÄ ofertÄ"
cancel: "anuluj"
edit:
title: "Edytuj ofertÄ"
submit: "Zapisz zmiany"
destroy: "usuÅ"
destroy_confirm: "Czy na pewno chcesz usunÄ
Ä ofertÄ?"
fieldset:
job_details: "SzczegóÅy oferty pracy"
apply_online: "Aplikuj online"
company_details: "Firma zatrudniajÄ
ca lub osoba zlecajÄ
ca"
human_test: "Czy jesteÅ czÅowiekiem"
type:
full_time: "etat"
freelance: "zlecenie"
free: "wolontariat"
practice: "praktyka"
remote: "praca zdalna"
type_long:
full_time: "poszukiwanie wspóÅpracowników / oferta pracy"
freelance: "zlecenie (konkretna usÅuga do wykonania)"
free: "wolontariat (praca za reklamy, bannery, itp. lub praca za darmo)"
practice: "staż/praktyka"
layout:
popular: "Najpopularniejsze"
latest: "Najnowsze"
menu:
main: "Strona gÅówna"
search: "Szukaj"
about: "O serwisie"
terms: "Regulamin"
follow: "Obserwuj nas"
contact: "Kontakt"
sidebar:
post_job: "Dodaj ofertÄ za DARMO!"
type: "typ"
localization: "lokalizacje"
language: "jÄzyk"
frameworks: "framework"
home:
title: "najpopularniejsze i najnowsze oferty pracy z IT"
popular: "Najpopularniejsze"
latest: "Najnowsze"
jobs: "oferty"
more_jobs: "pokaż wiÄcej ofert"
number:
format:
separator: ","
delimiter: " "
precision: 2
currency:
format:
format: "%n %u"
unit: "PLN"
percentage:
format:
delimiter: ""
precision:
format:
delimiter: ""
human:
format:
delimiter: ""
precision: 1
storage_units:
format: "%n %u"
units:
byte:
one: "bajt"
other: "bajty"
kb: "KB"
mb: "MB"
gb: "GB"
tb: "TB"
date:
formats:
default: "%Y-%m-%d"
short: "%d %b"
school: "%Y"
simple: "%d.%m.%Y"
long: "%d %B %Y"
day_names: [Niedziela, PoniedziaÅek, Wtorek, Åroda, Czwartek, PiÄ
tek, Sobota]
abbr_day_names: [nie, pon, wto, Åro, czw, pia, sob]
month_names: [~, StyczeÅ, Luty, Marzec, KwiecieÅ, Maj, Czerwiec, Lipiec, SierpieÅ, WrzesieÅ, Październik, Listopad, GrudzieÅ]
abbr_month_names: [~, sty, lut, mar, kwi, maj, cze, lip, sie, wrz, paź, lis, gru]
order: [ :year, :month, :day ]
time:
formats:
default: "%a, %d %b %Y, %H:%M:%S %z"
short: "%d %b, %H:%M"
long: "%d %B %Y, %H:%M"
am: "przed poÅudniem"
pm: "po poÅudniu"
datetime:
distance_in_words:
ago: "temu"
half_a_minute: "póŠminuty"
less_than_x_seconds:
one: "mniej niż sekundÄ"
few: "mniej niż {{count}} sekundy"
other: "mniej niż {{count}} sekund"
x_seconds:
one: "sekundÄ"
few: "{{count}} sekundy"
other: "{{count}} sekund"
less_than_x_minutes:
one: "mniej niż minutÄ"
few: "mniej niż {{count}} minuty"
other: "mniej niż {{count}} minut"
x_minutes:
one: "minutÄ"
few: "{{count}} minuty"
other: "{{count}} minut"
about_x_hours:
one: "okoÅo godziny"
other: "okoÅo {{count}} godzin"
x_days:
one: "1 dzieÅ"
other: "{{count}} dni"
about_x_months:
one: "okoÅo miesiÄ
ca"
other: "okoÅo {{count}} miesiÄcy"
x_months:
one: "1 miesiÄ
c"
few: "{{count}} miesiÄ
ce"
other: "{{count}} miesiÄcy"
about_x_years:
one: "okoÅo roku"
other: "okoÅo {{count}} lat"
over_x_years:
one: "ponad rok"
few: "ponad {{count}} lata"
other: "ponad {{count}} lat"
activerecord:
models:
user: "Użytkownik"
job: "Praca"
search: "Wyszukiwarka"
applicant: "Aplikant"
comment:
attributes:
captcha_solution:
blank: 'musi byÄ podane'
invalid: 'odpowiedź jest niepoprawna'
errors:
template:
header:
one: "{{model}} nie zostaÅ zachowany z powodu jednego bÅÄdu"
other: "{{model}} nie zostaÅ zachowany z powodu {{count}} bÅÄdów"
body: "BÅÄdy dotyczÄ
nastÄpujÄ
cych pól:"
messages:
inclusion: "nie znajduje siÄ na liÅcie dopuszczalnych wartoÅci"
exclusion: "znajduje siÄ na liÅcie zabronionych wartoÅci"
invalid: "jest nieprawidÅowe"
confirmation: "nie zgadza siÄ z potwierdzeniem"
accepted: "musi byÄ zaakceptowane"
empty: "nie może byÄ puste"
blank: "nie może byÄ puste"
too_long: "jest za dÅugie (maksymalnie {{count}} znaków)"
too_short: "jest za krótkie (minimalnie {{count}} znaków)"
wrong_length: "jest nieprawidÅowej dÅugoÅci (powinna wynosiÄ {{count}} znaków)"
taken: "zostaÅo już zajÄte"
not_a_number: "nie jest liczbÄ
"
greater_than: "musi byÄ wiÄksze niż {{count}}"
greater_than_or_equal_to: "musi byÄ wiÄksze lub równe {{count}}"
equal_to: "musi byÄ równe {{count}}"
less_than: "musi byÄ mniejsze niż {{count}}"
less_than_or_equal_to: "musi byÄ mniejsze lub równe {{count}}"
odd: "musi byÄ nieparzyste"
even: "musi byÄ parzyste"
record_invalid: "nieprawidÅowe dane"
support:
array:
sentence_connector: "i"
skip_last_comma: true
words_connector: ", "
two_words_connector: " i "
last_word_connector: " oraz "
for_word_connector: " dla "
in_word_connector: " w "
or_word_connector: " albo "
diff --git a/config/routes.rb b/config/routes.rb
index 344e157..e7634ad 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -1,90 +1,90 @@
ActionController::Routing::Routes.draw do |map|
map.new_contact '/contact/new', :controller => 'contact', :action => 'new', :conditions => { :method => :get }
map.contact '/contact', :controller => 'contact', :action => 'new', :conditions => { :method => :get }
map.contact '/contact', :controller => 'contact', :action => 'create', :conditions => { :method => :post }
- map.seo_page '/strona/:id/', :controller => 'admin/pages', :action => 'show'
+ map.seo_page '/page/:id/', :controller => 'admin/pages', :action => 'show'
map.with_options :controller => 'jobs', :action => 'index' do |job|
- job.with_options :category => nil, :page => 1, :order => "najnowsze", :requirements => { :order => /(najnowsze|najpopularniejsze)/, :page => /\d/ } do |seo|
- seo.connect '/oferty/:page'
- seo.connect '/oferty/:order'
- seo.connect '/oferty/:order/:page'
- seo.seo_jobs '/oferty/:order/:category/:page'
+ job.with_options :category => nil, :page => 1, :order => "latest", :requirements => { :order => /(latest|popular)/, :page => /\d/ } do |seo|
+ seo.connect '/jobs/:page'
+ seo.connect '/jobs/:order'
+ seo.connect '/jobs/:order/:page'
+ seo.seo_jobs '/jobs/:order/:category/:page'
end
- job.connect '/lokalizacja/:localization/:page'
- job.localization '/lokalizacja/:localization'
+ job.connect '/localization/:localization/:page'
+ job.localization '/localization/:localization'
job.connect '/framework/:framework/:page'
job.framework '/framework/:framework'
- job.connect '/jezyk/:language/:page'
- job.language '/jezyk/:language'
- job.connect '/typ/:type_id/:page'
- job.job_type '/typ/:type_id'
- job.connect '/kategoria/:category/:page'
- job.job_category '/kategoria/:category'
+ job.connect '/language/:language/:page'
+ job.language '/language/:language'
+ job.connect '/type/:type_id/:page'
+ job.job_type '/type/:type_id'
+ job.connect '/category/:category/:page'
+ job.job_category '/category/:category'
end
map.resources :jobs, :member => { :publish => :get, :destroy => :any }, :collection => { :search => :any, :widget => :get } do |jobs|
jobs.resources :applicants, :member => { :download => :get }
end
map.resource :widget
map.resources :user_sessions
map.login '/login', :controller => 'user_sessions', :action => 'new'
map.logout '/logout', :controller => 'user_sessions', :action => 'destroy'
map.namespace :admin do |admin|
admin.stats '/stats', :controller => "stats"
admin.config '/config', :controller => "configs", :action => "new"
admin.resources :pages
admin.resources :jobs
admin.resource :configs
admin.resources :frameworks
admin.resources :categories, :collection => { :reorder => :post }
end
map.admin '/admin', :controller => "admin/stats"
# The priority is based upon order of creation: first created -> highest priority.
# Sample of regular route:
# map.connect 'products/:id', :controller => 'catalog', :action => 'view'
# Keep in mind you can assign values other than :controller and :action
# Sample of named route:
# map.purchase 'products/:id/purchase', :controller => 'catalog', :action => 'purchase'
# This route can be invoked with purchase_url(:id => product.id)
# Sample resource route (maps HTTP verbs to controller actions automatically):
# map.resources :products
# Sample resource route with options:
# map.resources :products, :member => { :short => :get, :toggle => :post }, :collection => { :sold => :get }
# Sample resource route with sub-resources:
# map.resources :products, :has_many => [ :comments, :sales ], :has_one => :seller
# Sample resource route with more complex sub-resources
# map.resources :products do |products|
# products.resources :comments
# products.resources :sales, :collection => { :recent => :get }
# end
# Sample resource route within a namespace:
# map.namespace :admin do |admin|
# # Directs /admin/products/* to Admin::ProductsController (app/controllers/admin/products_controller.rb)
# admin.resources :products
# end
map.root :controller => "jobs", :action => "home"
map.seo_job '/:id', :controller => 'jobs', :action => 'show'
# You can have the root of your site routed with map.root -- just remember to delete public/index.html.
# See how all your routes lay out with "rake routes"
# Install the default routes as the lowest priority.
# Note: These default routes make all actions in every controller accessible via GET requests. You should
# consider removing or commenting them out if you're using named routes and resources.
map.connect ':controller/:action/:id'
map.connect ':controller/:action/:id.:format'
end
|
macbury/webpraca
|
52f2b1ef4fd55f222979c5063eb4efd5a25129f1
|
Job posted i18n
|
diff --git a/app/views/job_mailer/job_posted.erb b/app/views/job_mailer/job_posted.erb
index b253158..46a8ae5 100644
--- a/app/views/job_mailer/job_posted.erb
+++ b/app/views/job_mailer/job_posted.erb
@@ -1,13 +1,13 @@
-Witaj <%= @job.company_name %>!,
+<%= t('mailer.job_posted.greetings') %> <%= @job.company_name %>!,
-Aby opublikowaÄ swojÄ
ofertÄ kliknij na link poniżej:
+<%= t('mailer.job_posted.publish') %>:
<%= @publish_path %>
-Twoja oferta zostaÅa dodana i znajduje siÄ poda adresem:
+<%= t('mailer.job_posted.path_to_job') %>:
<%= @job_path %>
-Jeżeli chcesz wprowadziÄ zmiany w ofercie kliknij na link poniżej:
+<%= t('mailer.job_posted.path_to_edit_job') %>:
<%= @edit_path %>
-Aby usunÄ
Ä ofertÄ kliknij na poniższy link:
+<%= t('mailer.job_posted.path_to_destroy_job') %>:
<%= @destroy_path %>
diff --git a/app/views/jobs/_jobs.html.erb b/app/views/jobs/_jobs.html.erb
index 0badf79..661cb49 100644
--- a/app/views/jobs/_jobs.html.erb
+++ b/app/views/jobs/_jobs.html.erb
@@ -1,17 +1,17 @@
<% if jobs.nil? || jobs.empty? %>
- <p class="info">Brak ofert</p>
+ <p class="info"><%= t('jobs.empty') %></p>
<% else %>
<ul class="list">
<% jobs.each do |job| %>
<li class="<%= cycle('normal', 'alt') %>">
<span class="rank"><%= format_rank(job.rank) %></span>
<%= job_label(job) %>
<%= link_to job.title, seo_job_path(job), :class => job.highlighted? ? 'ranked' : nil %><%= t('support.array.for_word_connector') %><%= job_company(job) %> / <%= link_to job.localization.name, localization_path(job.localization) %>
<abbr class="date" title="<%= job.created_at.xmlschema %>">
<%= distance_of_time_in_words_to_now job.created_at %> <%= t('datetime.distance_in_words.ago') %>
</abbr>
</li>
<% end %>
</ul>
<%= will_paginate jobs if jobs.respond_to?(:total_pages) %>
<% end %>
\ No newline at end of file
diff --git a/app/views/jobs/show.html.erb b/app/views/jobs/show.html.erb
index a8eff1d..d76ab2a 100644
--- a/app/views/jobs/show.html.erb
+++ b/app/views/jobs/show.html.erb
@@ -1,88 +1,82 @@
<div class="box">
<div>
<div class="title">
<h2>
<%= @job.title %>
</h2>
</div>
<dl>
- <dt>Typ</dt>
+ <dt><%= t('jobs.show.type') %></dt>
<dd><%= job_label(@job) %></dd>
- <dt>Kategoria</dt>
+ <dt><%= t('jobs.show.category') %></dt>
<dd><%= link_to @job.category.name, job_category_path(@job.category) %></dd>
- <dt>Ocena</dt>
+ <dt><%= t('jobs.show.rank') %></dt>
<dd><%= format_rank(@job.rank) %></dd>
- <dt>Pracodawca</dt>
+ <dt><%= t('jobs.show.employer') %></dt>
<dd><%= link_to @job.company_name, @job.website, :target => "_blank" %></dd>
- <dt>Lokalizacja</dt>
+ <dt><%= t('jobs.show.localization') %></dt>
<dd><%= link_to @job.localization.name, localization_path(@job.localization) %></dd>
<% unless @job.framework.nil? %>
- <dt>Framework</dt>
+ <dt><%= t('jobs.show.framework') %></dt>
<dd><%= link_to @job.framework.name, framework_path(@job.framework) %></dd>
<% end %>
<% unless @job.language.nil? %>
- <dt>JÄzyk</dt>
+ <dt><%= t('jobs.show.language') %></dt>
<dd><%= link_to @job.language.name, language_path(@job.language) %></dd>
<% end %>
<% if @job.pay_band? %>
- <dt>WideÅko zarobkowe</dt>
+ <dt><%= t('jobs.show.pay_band') %></dt>
<dd>
<%= "od #{number_to_currency(@job.price_from)}" unless @job.price_from.nil? %>
<%= "do #{number_to_currency(@job.price_to)}" unless @job.price_to.nil? %> na miesiÄ
c, netto
</dd>
<% end %>
<% unless @job.apply_online %>
- <dt>Kontakt</dt>
+ <dt><%= t('jobs.show.contact') %></dt>
<dd><%= link_to "Formularz kontaktowy", contact_path(:job_id => @job.id) %></dd>
<% end %>
<% unless (@job.regon.nil? || @job.regon.empty?) %>
<dt>REGON</dt>
<dd><%= @job.regon %> </dd>
<% end %>
<% unless (@job.nip.nil? || @job.nip.empty?) %>
<dt>NIP</dt>
<dd><%= @job.nip %> </dd>
<% end %>
<% unless (@job.krs.nil? || @job.krs.empty?) %>
<dt>KRS</dt>
<dd><%= link_to @job.krs, "http://krs.ms.gov.pl/Podmiot.aspx?nrkrs=#{@job.krs}", :target => "_blank" %> </dd>
<% end %>
- <dt>Data rozpoczÄcia</dt>
+ <dt><%= t('jobs.show.published_at') %></dt>
<dd>
<%= l @job.created_at, :format => :long %>
<br />
- <abbr title="<%= @job.created_at.xmlschema %>"><%= distance_of_time_in_words_to_now @job.created_at %> temu</abbr>
+ <abbr title="<%= @job.created_at.xmlschema %>"><%= distance_of_time_in_words_to_now @job.created_at %> <%= t('datetime.distance_in_words.ago') %></abbr>
</dd>
- <dt>Data zakoÅczenia</dt>
+ <dt><%= t('jobs.show.end_at') %></dt>
<dd>
<%= l @job.end_at, :format => :long %>
<br />
za <abbr title="<%= @job.end_at.xmlschema %>"><%= distance_of_time_in_words_to_now(@job.end_at) %></abbr>
</dd>
- <dt>WyÅwietlona</dt>
+ <dt><%= t('jobs.show.visited') %></dt>
<dd><%= @job.visits_count %> razy</dd>
</dl>
<div class="clear"></div>
</div>
<div>
<div class="title mini">
- <h3>Opis oferty</h3>
+ <h3><%= t('jobs.show.description') %></h3>
</div>
<div class="text">
<%= RedCloth.new(highlight(@job.description, @tags, :highlighter => '<i>\1</i>')).to_html %>
</div>
- <p>
- <% if permitted_to? :edit, @job %>
- <%= link_to 'Edytuj', edit_job_path(@job) %> |
- <%= link_to 'Wstecz', jobs_path %>
- <% end %>
- </p>
</div>
- <%= link_to 'Aplikuj online!', new_job_applicant_path(@job), :class => "more", :rel => "nofollow" if @job.apply_online %>
+ <%= link_to t('jobs.show.apply_online'), new_job_applicant_path(@job), :class => "more", :rel => "nofollow" if @job.apply_online %>
</div>
diff --git a/config/locales/pl.yml b/config/locales/pl.yml
index 1372192..df5a5dd 100644
--- a/config/locales/pl.yml
+++ b/config/locales/pl.yml
@@ -1,255 +1,278 @@
# Polish translations for Ruby on Rails
# by Jacek Becela (jacek.becela@gmail.com, http://github.com/ncr)
pl:
+ mailer:
+ job_posted:
+ greetings: "Witaj"
+ publish: "Aby opublikowaÄ swojÄ
ofertÄ kliknij na link poniżej"
+ path_to_job: "Twoja oferta zostaÅa dodana i znajduje siÄ poda adresem:"
+ path_to_edit_job: "Jeżeli chcesz wprowadziÄ zmiany w ofercie kliknij na link poniżej"
+ path_to_destroy_job: "Aby usunÄ
Ä ofertÄ kliknij na poniższy link"
formtastic:
labels:
websiteconfig:
groups:
website: "Strona WWW"
js: "Skrypty"
js:
google_analytics: "Google Analytics"
widget: "Reklama"
website:
name: "Nazwa"
tags: "SÅowa kluczowe"
description: "Opis"
applicant:
email: "Twój E-Mail"
body: "TreÅÄ"
cv: "Dodaj ofertÄ/CV"
job:
title: "TytuÅ"
place_id: "Lokalizacja"
description: "Opis"
availability_time: "DÅugoÅÄ trwania"
remote_job: "Praca zdalna"
type_id: "Typ"
category_id: "Kategoria"
company_name: "Nazwa"
website: "Strona WWW"
framework_name: "Framework"
localization_id: "Lokalizacja"
apply_online: "Aplikuj online"
email_title: "TytuÅ emaila"
language: "JÄzyk"
pay_band: "WideÅki zarobkowe"
pay_band_detail: "PLN na miesiÄ
c, netto"
captcha: 'Kod z obrazka*'
user:
password: "HasÅo"
password_confirmation: "Powtórz hasÅo"
hints:
job:
availability_time: "ile dni oferta ma byÄ ważna(od 1 do 60 dni)"
localization_id: "np. 'Warszawa', 'Kraków, UK'"
framework_id: "gÅówny framework którego znajomoÅÄ jest wymagana, podaj peÅnÄ
nazwÄ"
apply_online: "uaktywnia formularz umożliwiajÄ
cy przesyÅanie aplikacji online w ofercie"
email_title: "np. MÅodszy programista, Ruby Developer/18/12/71 itp"
email: "Pod wskazany adres zostanÄ
przesÅane linki do edycji oferty, nie bÄdzie on widoczny publicznie(zamiast niego bÄdzie dostÄpny formularz kontaktowy)."
website: "zaczynajÄ
cy siÄ od http://"
flash:
notice:
email_verification: "Na twój e-mail zostaÅ wysÅany link którym opublikujesz ofertÄ."
job_updated: "Zapisano zmiany w ofercie."
job_published: "Twoja oferta jest już widoczna!"
job_deleted: "Oferta zostaÅa usuniÄta"
title:
popular: "najpopularniejsze oferty pracy IT"
latest: "najnowsze oferty pracy IT"
search: "Szukaj oferty"
finded_jobs: "Znalezione oferty"
jobs: "Oferty pracy IT"
jobs:
+ empty: "Brak ofert"
+ show:
+ type: "Typ"
+ category: "Kategoria"
+ rank: "Ocena"
+ employer: "Pracodawca"
+ localization: "Localization"
+ framework: "Framework"
+ language: "JÄzyk"
+ pay_band: "WideÅko zarobkowe"
+ contact: "Kontakt"
+ published_at: "Data rozpoczÄcia"
+ end_at: "Data zakoÅczenia"
+ visited: "WyÅwietlona"
+ description: "Opis oferty"
+ apply_online: "Aplikuj online!"
form:
new:
title: "Nowa oferta"
submit: "Zgadzam siÄ z regulaminem i chcÄ dodaÄ ofertÄ"
cancel: "anuluj"
edit:
title: "Edytuj ofertÄ"
submit: "Zapisz zmiany"
destroy: "usuÅ"
destroy_confirm: "Czy na pewno chcesz usunÄ
Ä ofertÄ?"
fieldset:
job_details: "SzczegóÅy oferty pracy"
apply_online: "Aplikuj online"
company_details: "Firma zatrudniajÄ
ca lub osoba zlecajÄ
ca"
human_test: "Czy jesteÅ czÅowiekiem"
type:
full_time: "etat"
freelance: "zlecenie"
free: "wolontariat"
practice: "praktyka"
remote: "praca zdalna"
type_long:
full_time: "poszukiwanie wspóÅpracowników / oferta pracy"
freelance: "zlecenie (konkretna usÅuga do wykonania)"
free: "wolontariat (praca za reklamy, bannery, itp. lub praca za darmo)"
practice: "staż/praktyka"
layout:
popular: "Najpopularniejsze"
latest: "Najnowsze"
menu:
main: "Strona gÅówna"
search: "Szukaj"
about: "O serwisie"
terms: "Regulamin"
follow: "Obserwuj nas"
contact: "Kontakt"
sidebar:
post_job: "Dodaj ofertÄ za DARMO!"
type: "typ"
localization: "lokalizacje"
language: "jÄzyk"
frameworks: "framework"
home:
title: "najpopularniejsze i najnowsze oferty pracy z IT"
popular: "Najpopularniejsze"
latest: "Najnowsze"
jobs: "oferty"
more_jobs: "pokaż wiÄcej ofert"
number:
format:
separator: ","
delimiter: " "
precision: 2
currency:
format:
format: "%n %u"
unit: "PLN"
percentage:
format:
delimiter: ""
precision:
format:
delimiter: ""
human:
format:
delimiter: ""
precision: 1
storage_units:
format: "%n %u"
units:
byte:
one: "bajt"
other: "bajty"
kb: "KB"
mb: "MB"
gb: "GB"
tb: "TB"
date:
formats:
default: "%Y-%m-%d"
short: "%d %b"
school: "%Y"
simple: "%d.%m.%Y"
long: "%d %B %Y"
day_names: [Niedziela, PoniedziaÅek, Wtorek, Åroda, Czwartek, PiÄ
tek, Sobota]
abbr_day_names: [nie, pon, wto, Åro, czw, pia, sob]
month_names: [~, StyczeÅ, Luty, Marzec, KwiecieÅ, Maj, Czerwiec, Lipiec, SierpieÅ, WrzesieÅ, Październik, Listopad, GrudzieÅ]
abbr_month_names: [~, sty, lut, mar, kwi, maj, cze, lip, sie, wrz, paź, lis, gru]
order: [ :year, :month, :day ]
time:
formats:
default: "%a, %d %b %Y, %H:%M:%S %z"
short: "%d %b, %H:%M"
long: "%d %B %Y, %H:%M"
am: "przed poÅudniem"
pm: "po poÅudniu"
datetime:
distance_in_words:
ago: "temu"
half_a_minute: "póŠminuty"
less_than_x_seconds:
one: "mniej niż sekundÄ"
few: "mniej niż {{count}} sekundy"
other: "mniej niż {{count}} sekund"
x_seconds:
one: "sekundÄ"
few: "{{count}} sekundy"
other: "{{count}} sekund"
less_than_x_minutes:
one: "mniej niż minutÄ"
few: "mniej niż {{count}} minuty"
other: "mniej niż {{count}} minut"
x_minutes:
one: "minutÄ"
few: "{{count}} minuty"
other: "{{count}} minut"
about_x_hours:
one: "okoÅo godziny"
other: "okoÅo {{count}} godzin"
x_days:
one: "1 dzieÅ"
other: "{{count}} dni"
about_x_months:
one: "okoÅo miesiÄ
ca"
other: "okoÅo {{count}} miesiÄcy"
x_months:
one: "1 miesiÄ
c"
few: "{{count}} miesiÄ
ce"
other: "{{count}} miesiÄcy"
about_x_years:
one: "okoÅo roku"
other: "okoÅo {{count}} lat"
over_x_years:
one: "ponad rok"
few: "ponad {{count}} lata"
other: "ponad {{count}} lat"
activerecord:
models:
user: "Użytkownik"
job: "Praca"
search: "Wyszukiwarka"
applicant: "Aplikant"
comment:
attributes:
captcha_solution:
blank: 'musi byÄ podane'
invalid: 'odpowiedź jest niepoprawna'
errors:
template:
header:
one: "{{model}} nie zostaÅ zachowany z powodu jednego bÅÄdu"
other: "{{model}} nie zostaÅ zachowany z powodu {{count}} bÅÄdów"
body: "BÅÄdy dotyczÄ
nastÄpujÄ
cych pól:"
messages:
inclusion: "nie znajduje siÄ na liÅcie dopuszczalnych wartoÅci"
exclusion: "znajduje siÄ na liÅcie zabronionych wartoÅci"
invalid: "jest nieprawidÅowe"
confirmation: "nie zgadza siÄ z potwierdzeniem"
accepted: "musi byÄ zaakceptowane"
empty: "nie może byÄ puste"
blank: "nie może byÄ puste"
too_long: "jest za dÅugie (maksymalnie {{count}} znaków)"
too_short: "jest za krótkie (minimalnie {{count}} znaków)"
wrong_length: "jest nieprawidÅowej dÅugoÅci (powinna wynosiÄ {{count}} znaków)"
taken: "zostaÅo już zajÄte"
not_a_number: "nie jest liczbÄ
"
greater_than: "musi byÄ wiÄksze niż {{count}}"
greater_than_or_equal_to: "musi byÄ wiÄksze lub równe {{count}}"
equal_to: "musi byÄ równe {{count}}"
less_than: "musi byÄ mniejsze niż {{count}}"
less_than_or_equal_to: "musi byÄ mniejsze lub równe {{count}}"
odd: "musi byÄ nieparzyste"
even: "musi byÄ parzyste"
record_invalid: "nieprawidÅowe dane"
support:
array:
sentence_connector: "i"
skip_last_comma: true
words_connector: ", "
two_words_connector: " i "
last_word_connector: " oraz "
for_word_connector: " dla "
in_word_connector: " w "
or_word_connector: " albo "
|
macbury/webpraca
|
bccffd3b5845516d8eca96d4fa67229b56b79043
|
i18n new job form
|
diff --git a/app/stylesheets/formtastic_changes.less b/app/stylesheets/formtastic_changes.less
index c1392d9..cd9cdb1 100644
--- a/app/stylesheets/formtastic_changes.less
+++ b/app/stylesheets/formtastic_changes.less
@@ -1,21 +1,21 @@
/* -------------------------------------------------------------------------------------------------
Load this stylesheet after formtastic.css in your layouts to override the CSS to suit your needs.
This will allow you to update formtastic.css with new releases without clobbering your own changes.
For example, to make the inline hint paragraphs a little darker in color than the standard #666:
form.formtastic fieldset ol li p.inline-hints { color:#333; }
--------------------------------------------------------------------------------------------------*/
form.formtastic fieldset ol li fieldset legend { position: static; }
form.formtastic fieldset ol li p.inline-hints { clear: both; }
form.formtastic fieldset ol li > div { margin-left: 25%; }
form.formtastic fieldset ol li label { padding-top: 0.4em; }
form.formtastic p.inline-errors { color:#cc0000; }
form.formtastic #recaptcha_widget_div { margin-left: 25%; }
form.formtastic .markItUpButton { margin-bottom: 2px !important; }
-form.formtastic .markItUpEditor { width: 99%; }
+form.formtastic .markItUpEditor, #job_description { width: 99%; }
form.formtastic .check_boxes.columns li { float: left; width: 33%; }
form.formtastic fieldset ol li.numeric input, form.formtastic fieldset ol li.string input, form.formtastic fieldset ol li.text textarea, form.formtastic fieldset ol li.password input { width: 73%; }
\ No newline at end of file
diff --git a/app/views/jobs/_form.html.erb b/app/views/jobs/_form.html.erb
index 9b76059..d7f2dd6 100644
--- a/app/views/jobs/_form.html.erb
+++ b/app/views/jobs/_form.html.erb
@@ -1,60 +1,56 @@
<%= hidden_field_tag 'token', params[:token] unless params[:token].nil? %>
-<% form.inputs :name => 'SzczegóÅy oferty pracy' do %>
+<% form.inputs :name => t('jobs.form.fieldset.job_details') do %>
<%= form.input :title %>
<%= form.input :category_id, :as => :select, :collection => Category.all.map { |c| [c.name, c.id] } %>
<li class="select">
- <%= form.label :localization_id, 'Lokalizacja*' %>
- <%= form.select :localization_id, Localization.all(:order => 'name').map { |localization| [localization.name, localization.id] } %> albo
+ <%= form.label :localization_id, t('formtastic.labels.job.localization_id')+'*' %>
+ <%= form.select :localization_id, Localization.all(:order => 'name').map { |localization| [localization.name, localization.id] } %> <%= t('support.array.or_word_connector') %>
<%= form.text_field :localization_name %>
- <p class="inline-hints">np. 'Warszawa', 'Kraków, UK'</p>
+ <p class="inline-hints"><%= t('formtastic.hints.job.localization_id') %></p>
<%= inline_errors @job, :localization_name %>
</li>
- <%= form.input :type_id, :as => :radio, :collection => collection_from_types(JOB_TYPES) %>
+ <%= form.input :type_id, :as => :radio, :collection => JOB_TYPES.enum_for(:each_with_index).map { |type, index| [t("jobs.type_long.#{type}"), index] } %>
<%= form.input :remote_job, :required => false %>
- <%= form.input :availability_time, :as => :numeric, :hint => "ile dni oferta ma byÄ ważna(od 1 do 60 dni)" %>
+ <%= form.input :availability_time, :as => :numeric %>
<%= form.input :language, :collection => Language.all(:order => 'name').map { |l| [l.name, l.id] }, :include_blank => true, :required => false %>
<li class="select">
<%= form.label :framework_id, 'Framework' %>
- <%= form.select :framework_id, Framework.all(:order => 'name').map { |frame| [frame.name, frame.id] }, :include_blank => true %> albo
+ <%= form.select :framework_id, Framework.all(:order => 'name').map { |frame| [frame.name, frame.id] }, :include_blank => true %> <%= t('support.array.or_word_connector') %>
<%= form.text_field :framework_name %>
- <p class="inline-hints">gÅówny framework którego znajomoÅÄ jest wymagana, podaj peÅnÄ
nazwÄ</p>
+ <p class="inline-hints"><%= t('formtastic.hints.job.framework_id') %></p>
<%= inline_errors @job, :framework_name %>
</li>
<li class="numeric prices">
- <label>WideÅki zarobkowe:</label>
- <%= form.text_field :price_from %> do <%= form.text_field :price_to %> PLN na miesiÄ
c, netto
+ <label><%= t('formtastic.labels.job.pay_band') %></label>
+ <%= form.text_field :price_from %> - <%= form.text_field :price_to %> <%= t('formtastic.labels.job.pay_band_detail') %>
<%= inline_errors @job, :price_from %>
<%= inline_errors @job, :price_to %>
</li>
- <li>
- <%= form.label :description, 'Opis*' %>
- <%= form.text_area :description %>
- <%= inline_errors @job, :description %>
- </li>
+ <%= form.input :description %>
+
<% end %>
-<% form.inputs :name => "Aplikuj online" do %>
- <%= form.input :apply_online, :required => false, :hint => "uaktywnia formularz umożliwiajÄ
cy przesyÅanie aplikacji online w ofercie" %>
- <%= form.input :email_title, :required => false, :hint => "np. MÅodszy programista, Ruby Developer/18/12/71 itp" %>
+<% form.inputs :name => t('jobs.form.fieldset.apply_online') do %>
+ <%= form.input :apply_online, :required => false %>
+ <%= form.input :email_title, :required => false %>
<% end %>
-<% form.inputs :name => 'Firma zatrudniajÄ
ca lub osoba zlecajÄ
ca' do %>
- <%= form.input :email, :hint => "Pod wskazany adres zostanÄ
przesÅane linki do edycji oferty, nie bÄdzie on widoczny publicznie(zamiast niego bÄdzie dostÄpny formularz kontaktowy)." %>
+<% form.inputs :name => t('jobs.form.fieldset.company_details') do %>
+ <%= form.input :email %>
<%= form.input :company_name %>
- <%= form.input :website, :hint => "zaczynajÄ
cy siÄ od http://", :required => false %>
+ <%= form.input :website, :required => false %>
<%= form.input :nip, :required => false %>
<%= form.input :regon, :required => false %>
<%= form.input :krs, :required => false %>
<% end %>
<% if @job.new_record? %>
- <% form.inputs :name => "Czy jesteÅ czÅowiekiem" do %>
+ <% form.inputs :name => t('jobs.form.fieldset.human_test') do %>
<li class="string required">
- <%= form.label :captcha, 'Kod z obrazka*' %>
+ <%= form.label :captcha, t('formtastic.labels.job.captcha') %>
<%= form.captcha_challenge %>
<%= form.captcha_field %>
<%= inline_errors @job, :captcha_solution %>
-
</li>
<% end %>
<% end %>
\ No newline at end of file
diff --git a/app/views/jobs/new.html.erb b/app/views/jobs/new.html.erb
index f627583..00748e2 100644
--- a/app/views/jobs/new.html.erb
+++ b/app/views/jobs/new.html.erb
@@ -1,20 +1,20 @@
-<% title @job.new_record? ? "Nowa oferta" : ["Edycja oferty", @job.title] %>
+<% title @job.new_record? ? t('jobs.form.new.title') : [t('jobs.form.edit.title'), @job.title] %>
<div class="box">
<div>
<div class="title">
- <h2><%= @job.new_record? ? "Nowa oferta" : "Edycja oferty" %></h2>
+ <h2><%= @job.new_record? ? t('jobs.form.new.title') : t('jobs.form.edit.title') %></h2>
</div>
<% semantic_form_for(@job) do |f| %>
<%= render :partial => "form", :object => f %>
<div class="buttons">
<div class="button">
- <%= f.submit @job.new_record? ? "Zgadzam siÄ z regulaminem i chcÄ dodaÄ ofertÄ" : "Zapisz zmiany" %>
+ <%= f.submit @job.new_record? ? t('jobs.form.new.submit') : t('jobs.form.edit.submit') %>
</div>
<% unless @job.new_record? %>
- , <%= link_to "usuÅ", @job, :method => :delete, :confirm => "Czy na pewno chcesz usunÄ
Ä ofertÄ?" %>
+ , <%= link_to t('jobs.form.edit.destroy'), @job, :method => :delete, :confirm => t('jobs.form.edit.destroy_confirm') %>
<% end %>
- albo <%= link_to 'anuluj', jobs_path %>
+ <%= t('support.array.or_word_connector') %> <%= link_to t('jobs.form.new.cancel'), jobs_path %>
</div>
<% end %>
</div>
</div>
\ No newline at end of file
diff --git a/config/initializers/formtastic.rb b/config/initializers/formtastic.rb
index 76f76a9..ef113eb 100644
--- a/config/initializers/formtastic.rb
+++ b/config/initializers/formtastic.rb
@@ -1,51 +1,51 @@
# Set the default text field size when input is a string. Default is 50.
# Formtastic::SemanticFormBuilder.default_text_field_size = 50
# Should all fields be considered "required" by default?
# Defaults to true, see ValidationReflection notes below.
# Formtastic::SemanticFormBuilder.all_fields_required_by_default = true
# Should select fields have a blank option/prompt by default?
# Defaults to true.
# Formtastic::SemanticFormBuilder.include_blank_for_select_by_default = true
# Set the string that will be appended to the labels/fieldsets which are required
# It accepts string or procs and the default is a localized version of
# '<abbr title="required">*</abbr>'. In other words, if you configure formtastic.required
# in your locale, it will replace the abbr title properly. But if you don't want to use
# abbr tag, you can simply give a string as below
# Formtastic::SemanticFormBuilder.required_string = "(required)"
# Set the string that will be appended to the labels/fieldsets which are optional
# Defaults to an empty string ("") and also accepts procs (see required_string above)
# Formtastic::SemanticFormBuilder.optional_string = "(optional)"
# Set the way inline errors will be displayed.
# Defaults to :sentence, valid options are :sentence, :list and :none
# Formtastic::SemanticFormBuilder.inline_errors = :sentence
# Set the method to call on label text to transform or format it for human-friendly
# reading when formtastic is user without object. Defaults to :humanize.
# Formtastic::SemanticFormBuilder.label_str_method = :humanize
# Set the array of methods to try calling on parent objects in :select and :radio inputs
# for the text inside each @<option>@ tag or alongside each radio @<input>@. The first method
# that is found on the object will be used.
# Defaults to ["to_label", "display_name", "full_name", "name", "title", "username", "login", "value", "to_s"]
# Formtastic::SemanticFormBuilder.collection_label_methods = [
# "to_label", "display_name", "full_name", "name", "title", "username", "login", "value", "to_s"]
# Formtastic by default renders inside li tags the input, hints and then
# errors messages. Sometimes you want the hints to be rendered first than
# the input, in the following order: hints, input and errors. You can
# customize it doing just as below:
# Formtastic::SemanticFormBuilder.inline_order = [:input, :hints, :errors]
# Specifies if labels/hints for input fields automatically be looked up using I18n.
# Default value: false. Overridden for specific fields by setting value to true,
# i.e. :label => true, or :hint => true (or opposite depending on initialized value)
-# Formtastic::SemanticFormBuilder.i18n_lookups_by_default = false
+Formtastic::SemanticFormBuilder.i18n_lookups_by_default = true
# You can add custom inputs or override parts of Formtastic by subclassing SemanticFormBuilder and
# specifying that class here. Defaults to SemanticFormBuilder.
# Formtastic::SemanticFormHelper.builder = MyCustomBuilder
diff --git a/config/locales/pl.yml b/config/locales/pl.yml
index 9ceed90..1372192 100644
--- a/config/locales/pl.yml
+++ b/config/locales/pl.yml
@@ -1,225 +1,255 @@
# Polish translations for Ruby on Rails
# by Jacek Becela (jacek.becela@gmail.com, http://github.com/ncr)
pl:
+ formtastic:
+ labels:
+ websiteconfig:
+ groups:
+ website: "Strona WWW"
+ js: "Skrypty"
+ js:
+ google_analytics: "Google Analytics"
+ widget: "Reklama"
+ website:
+ name: "Nazwa"
+ tags: "SÅowa kluczowe"
+ description: "Opis"
+ applicant:
+ email: "Twój E-Mail"
+ body: "TreÅÄ"
+ cv: "Dodaj ofertÄ/CV"
+ job:
+ title: "TytuÅ"
+ place_id: "Lokalizacja"
+ description: "Opis"
+ availability_time: "DÅugoÅÄ trwania"
+ remote_job: "Praca zdalna"
+ type_id: "Typ"
+ category_id: "Kategoria"
+ company_name: "Nazwa"
+ website: "Strona WWW"
+ framework_name: "Framework"
+ localization_id: "Lokalizacja"
+ apply_online: "Aplikuj online"
+ email_title: "TytuÅ emaila"
+ language: "JÄzyk"
+ pay_band: "WideÅki zarobkowe"
+ pay_band_detail: "PLN na miesiÄ
c, netto"
+ captcha: 'Kod z obrazka*'
+ user:
+ password: "HasÅo"
+ password_confirmation: "Powtórz hasÅo"
+ hints:
+ job:
+ availability_time: "ile dni oferta ma byÄ ważna(od 1 do 60 dni)"
+ localization_id: "np. 'Warszawa', 'Kraków, UK'"
+ framework_id: "gÅówny framework którego znajomoÅÄ jest wymagana, podaj peÅnÄ
nazwÄ"
+ apply_online: "uaktywnia formularz umożliwiajÄ
cy przesyÅanie aplikacji online w ofercie"
+ email_title: "np. MÅodszy programista, Ruby Developer/18/12/71 itp"
+ email: "Pod wskazany adres zostanÄ
przesÅane linki do edycji oferty, nie bÄdzie on widoczny publicznie(zamiast niego bÄdzie dostÄpny formularz kontaktowy)."
+ website: "zaczynajÄ
cy siÄ od http://"
flash:
notice:
email_verification: "Na twój e-mail zostaÅ wysÅany link którym opublikujesz ofertÄ."
job_updated: "Zapisano zmiany w ofercie."
job_published: "Twoja oferta jest już widoczna!"
job_deleted: "Oferta zostaÅa usuniÄta"
title:
popular: "najpopularniejsze oferty pracy IT"
latest: "najnowsze oferty pracy IT"
search: "Szukaj oferty"
finded_jobs: "Znalezione oferty"
jobs: "Oferty pracy IT"
jobs:
+ form:
+ new:
+ title: "Nowa oferta"
+ submit: "Zgadzam siÄ z regulaminem i chcÄ dodaÄ ofertÄ"
+ cancel: "anuluj"
+ edit:
+ title: "Edytuj ofertÄ"
+ submit: "Zapisz zmiany"
+ destroy: "usuÅ"
+ destroy_confirm: "Czy na pewno chcesz usunÄ
Ä ofertÄ?"
+ fieldset:
+ job_details: "SzczegóÅy oferty pracy"
+ apply_online: "Aplikuj online"
+ company_details: "Firma zatrudniajÄ
ca lub osoba zlecajÄ
ca"
+ human_test: "Czy jesteÅ czÅowiekiem"
type:
full_time: "etat"
freelance: "zlecenie"
free: "wolontariat"
practice: "praktyka"
remote: "praca zdalna"
type_long:
full_time: "poszukiwanie wspóÅpracowników / oferta pracy"
freelance: "zlecenie (konkretna usÅuga do wykonania)"
free: "wolontariat (praca za reklamy, bannery, itp. lub praca za darmo)"
practice: "staż/praktyka"
layout:
popular: "Najpopularniejsze"
latest: "Najnowsze"
menu:
main: "Strona gÅówna"
search: "Szukaj"
about: "O serwisie"
terms: "Regulamin"
follow: "Obserwuj nas"
contact: "Kontakt"
sidebar:
post_job: "Dodaj ofertÄ za DARMO!"
type: "typ"
localization: "lokalizacje"
language: "jÄzyk"
frameworks: "framework"
home:
title: "najpopularniejsze i najnowsze oferty pracy z IT"
popular: "Najpopularniejsze"
latest: "Najnowsze"
jobs: "oferty"
more_jobs: "pokaż wiÄcej ofert"
number:
format:
separator: ","
delimiter: " "
precision: 2
currency:
format:
format: "%n %u"
unit: "PLN"
percentage:
format:
delimiter: ""
precision:
format:
delimiter: ""
human:
format:
delimiter: ""
precision: 1
storage_units:
format: "%n %u"
units:
byte:
one: "bajt"
other: "bajty"
kb: "KB"
mb: "MB"
gb: "GB"
tb: "TB"
date:
formats:
default: "%Y-%m-%d"
short: "%d %b"
school: "%Y"
simple: "%d.%m.%Y"
long: "%d %B %Y"
day_names: [Niedziela, PoniedziaÅek, Wtorek, Åroda, Czwartek, PiÄ
tek, Sobota]
abbr_day_names: [nie, pon, wto, Åro, czw, pia, sob]
month_names: [~, StyczeÅ, Luty, Marzec, KwiecieÅ, Maj, Czerwiec, Lipiec, SierpieÅ, WrzesieÅ, Październik, Listopad, GrudzieÅ]
abbr_month_names: [~, sty, lut, mar, kwi, maj, cze, lip, sie, wrz, paź, lis, gru]
order: [ :year, :month, :day ]
time:
formats:
default: "%a, %d %b %Y, %H:%M:%S %z"
short: "%d %b, %H:%M"
long: "%d %B %Y, %H:%M"
am: "przed poÅudniem"
pm: "po poÅudniu"
datetime:
distance_in_words:
ago: "temu"
half_a_minute: "póŠminuty"
less_than_x_seconds:
one: "mniej niż sekundÄ"
few: "mniej niż {{count}} sekundy"
other: "mniej niż {{count}} sekund"
x_seconds:
one: "sekundÄ"
few: "{{count}} sekundy"
other: "{{count}} sekund"
less_than_x_minutes:
one: "mniej niż minutÄ"
few: "mniej niż {{count}} minuty"
other: "mniej niż {{count}} minut"
x_minutes:
one: "minutÄ"
few: "{{count}} minuty"
other: "{{count}} minut"
about_x_hours:
one: "okoÅo godziny"
other: "okoÅo {{count}} godzin"
x_days:
one: "1 dzieÅ"
other: "{{count}} dni"
about_x_months:
one: "okoÅo miesiÄ
ca"
other: "okoÅo {{count}} miesiÄcy"
x_months:
one: "1 miesiÄ
c"
few: "{{count}} miesiÄ
ce"
other: "{{count}} miesiÄcy"
about_x_years:
one: "okoÅo roku"
other: "okoÅo {{count}} lat"
over_x_years:
one: "ponad rok"
few: "ponad {{count}} lata"
other: "ponad {{count}} lat"
activerecord:
models:
user: "Użytkownik"
job: "Praca"
search: "Wyszukiwarka"
applicant: "Aplikant"
comment:
attributes:
captcha_solution:
blank: 'musi byÄ podane'
invalid: 'odpowiedź jest niepoprawna'
- attributes:
- websiteconfig:
- groups:
- website: "Strona WWW"
- js: "Skrypty"
- js:
- google_analytics: "Google Analytics"
- widget: "Reklama"
- website:
- name: "Nazwa"
- tags: "SÅowa kluczowe"
- description: "Opis"
- applicant:
- email: "Twój E-Mail"
- body: "TreÅÄ"
- cv: "Dodaj ofertÄ/CV"
- job:
- title: "TytuÅ"
- place_id: "Lokalizacja"
- description: "Opis"
- availability_time: "DÅugoÅÄ trwania"
- remote_job: "Praca zdalna"
- type_id: "Typ"
- category_id: "Kategoria"
- company_name: "Nazwa"
- website: "Strona WWW"
- framework_name: "Framework"
- apply_online: "Aplikuj online"
- email_title: "TytuÅ emaila"
- language: "JÄzyk"
- user:
- password: "HasÅo"
- password_confirmation: "Powtórz hasÅo"
errors:
template:
header:
one: "{{model}} nie zostaÅ zachowany z powodu jednego bÅÄdu"
other: "{{model}} nie zostaÅ zachowany z powodu {{count}} bÅÄdów"
body: "BÅÄdy dotyczÄ
nastÄpujÄ
cych pól:"
messages:
inclusion: "nie znajduje siÄ na liÅcie dopuszczalnych wartoÅci"
exclusion: "znajduje siÄ na liÅcie zabronionych wartoÅci"
invalid: "jest nieprawidÅowe"
confirmation: "nie zgadza siÄ z potwierdzeniem"
accepted: "musi byÄ zaakceptowane"
empty: "nie może byÄ puste"
blank: "nie może byÄ puste"
too_long: "jest za dÅugie (maksymalnie {{count}} znaków)"
too_short: "jest za krótkie (minimalnie {{count}} znaków)"
wrong_length: "jest nieprawidÅowej dÅugoÅci (powinna wynosiÄ {{count}} znaków)"
taken: "zostaÅo już zajÄte"
not_a_number: "nie jest liczbÄ
"
greater_than: "musi byÄ wiÄksze niż {{count}}"
greater_than_or_equal_to: "musi byÄ wiÄksze lub równe {{count}}"
equal_to: "musi byÄ równe {{count}}"
less_than: "musi byÄ mniejsze niż {{count}}"
less_than_or_equal_to: "musi byÄ mniejsze lub równe {{count}}"
odd: "musi byÄ nieparzyste"
even: "musi byÄ parzyste"
record_invalid: "nieprawidÅowe dane"
support:
array:
sentence_connector: "i"
skip_last_comma: true
words_connector: ", "
two_words_connector: " i "
last_word_connector: " oraz "
for_word_connector: " dla "
in_word_connector: " w "
+ or_word_connector: " albo "
|
macbury/webpraca
|
da1a3f366ab683c2ebf38643c2d78b821d444e12
|
i18n support
|
diff --git a/app/controllers/jobs_controller.rb b/app/controllers/jobs_controller.rb
index 0e86402..eb0f605 100644
--- a/app/controllers/jobs_controller.rb
+++ b/app/controllers/jobs_controller.rb
@@ -1,196 +1,196 @@
class JobsController < ApplicationController
validates_captcha :only => [:create, :new]
ads_pos :bottom
ads_pos :right, :except => [:home, :index, :search]
ads_pos :none, :only => [:home]
def home
- set_meta_tags :title => 'najpopularniejsze i najnowsze oferty pracy z IT',
+ set_meta_tags :title => t('home.title'),
:separator => " - "
query = Job.active.search
@recent_jobs = query.all(:order => "created_at DESC", :limit => 15, :include => [:localization, :category])
@top_jobs = query.all(:order => "rank DESC, created_at DESC", :limit => 15, :include => [:localization, :category])
end
# GET /jobs
# GET /jobs.xml
def index
@query = Job.active.search
options = {
:page => params[:page],
:per_page => 35,
:order => "created_at DESC, rank DESC",
:include => [:localization, :category]
}
if params[:order] =~ /najpopularniejsze/i
- @page_title = ['najpopularniejsze oferty pracy IT']
+ @page_title = [t('title.popular')]
@order = :rank
options[:order] = "rank DESC, created_at DESC"
else
@order = :created_at
- @page_title = ['najnowsze oferty pracy IT']
+ @page_title = [t('title.latest')]
options[:order] = "created_at DESC, rank DESC"
end
if params[:language]
@language = Language.find_by_permalink!(params[:language])
@page_title << @language.name.downcase
@query.language_id_is(@language.id)
end
if params[:category]
@category = Category.find_by_permalink!(params[:category])
@page_title << @category.name.downcase
@query.category_id_is(@category.id)
end
if params[:localization]
@localization = Localization.find_by_permalink!(params[:localization])
@page_title << @localization.name.downcase
@query.localization_id_is(@localization.id)
end
if params[:framework]
@framework = Framework.find_by_permalink!(params[:framework])
@page_title << @framework.name.downcase
options[:include] << :framework
@query.framework_id_is(@framework.id)
end
if params[:type_id]
- @type_id = JOB_LABELS.index(params[:type_id]) || 0
- @page_title << JOB_LABELS[@type_id].downcase
+ @type_id = JOB_TYPES.index(params[:type_id]) || 0
+ @page_title << JOB_TYPES[@type_id].downcase
@query.type_id_is(@type_id)
end
@jobs = @query.paginate(options)
respond_to do |format|
format.html # index.html.erb
format.rss
format.atom
end
end
def search
- @page_title = ["Szukaj oferty"]
+ @page_title = [t('title.search')]
@search = Job.active.search(params[:search])
if params[:search]
- @page_title = ["Znalezione oferty"]
+ @page_title = [t('title.finded_jobs')]
@jobs = @search.paginate( :page => params[:page],
:per_page => 30,
:order => "created_at DESC, rank DESC" )
end
respond_to do |format|
format.html
format.rss { render :action => "index" }
format.atom { render :action => "index" }
end
end
# GET /jobs/1
# GET /jobs/1.xml
def show
@job = Job.find_by_permalink!(params[:id])
@job.visited_by(request.remote_ip)
@category = @job.category
- @page_title = ["oferta pracy IT", @job.category.name.downcase, @job.localization.name.downcase, @job.company_name.downcase, @job.title.downcase]
+ @page_title = [t('title.jobs'), @job.category.name.downcase, @job.localization.name.downcase, @job.company_name.downcase, @job.title.downcase]
@tags = WebSiteConfig['website']['tags'].split(',').map(&:strip) + [@job.category.name, @job.localization.name, @job.company_name]
- @tags << JOB_LABELS[@job.type_id]
+ @tags << JOB_TYPES[@job.type_id]
unless @job.framework.nil?
@tags << @job.framework.name
@page_title.insert(1, @job.framework.name)
end
unless @job.language.nil?
@page_title.insert(1, @job.language.name)
@tags << @job.language.name
end
set_meta_tags :keywords => @tags.join(', ')
respond_to do |format|
format.html # show.html.erb
end
end
# GET /jobs/new
# GET /jobs/new.xml
def new
@job = Job.new
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @job }
end
end
# POST /jobs
# POST /jobs.xml
def create
@job = Job.new(params[:job])
respond_to do |format|
if @job.save
- flash[:notice] = 'Na twój e-mail zostaÅ wysÅany link którym opublikujesz ofertÄ.'
+ flash[:notice] = t('flash.notice.email_verification')
format.html { redirect_to(@job) }
format.xml { render :xml => @job, :status => :created, :location => @job }
else
format.html { render :action => "new" }
format.xml { render :xml => @job.errors, :status => :unprocessable_entity }
end
end
end
# GET /jobs/1/edit
def edit
@job = Job.find_by_permalink_and_token!(params[:id], params[:token])
render :action => "new"
end
# PUT /jobs/1
# PUT /jobs/1.xml
def update
@job = Job.find_by_permalink_and_token!(params[:id], params[:token])
respond_to do |format|
if @job.update_attributes(params[:job])
- flash[:notice] = 'Zapisano zmiany w ofercie.'
+ flash[:notice] = t('flash.notice.job_updated')
format.html { redirect_to(@job) }
format.xml { head :ok }
else
format.html { render :action => "new" }
format.xml { render :xml => @job.errors, :status => :unprocessable_entity }
end
end
end
def publish
@job = Job.find_by_permalink_and_token!(params[:id], params[:token])
unless @job.published
@job.publish!
- flash[:notice] = "Twoja oferta jest już widoczna!"
+ flash[:notice] = t('flash.notice.job_published')
end
redirect_to @job
end
# DELETE /jobs/1
# DELETE /jobs/1.xml
def destroy
@job = Job.find_by_permalink_and_token!(params[:id], params[:token])
@job.destroy
- flash[:notice] = "Oferta zostaÅa usuniÄta"
+ flash[:notice] = t('flash.notice.job_deleted')
respond_to do |format|
format.html { redirect_to(jobs_url) }
format.xml { head :ok }
end
end
end
diff --git a/app/controllers/widgets_controller.rb b/app/controllers/widgets_controller.rb
index 9534726..e9ffce6 100644
--- a/app/controllers/widgets_controller.rb
+++ b/app/controllers/widgets_controller.rb
@@ -1,36 +1,36 @@
class WidgetsController < ApplicationController
before_filter :widget_from_params
ads_pos :right
def new
end
def show
@jobs = Job.active.all(:order => "RANDOM(), rank DESC, created_at DESC", :limit => 15, :include => [:localization])
@jobs_hash = @jobs.map do |job|
{
:title => "#{job.title} dla #{job.company_name} w #{job.localization.name}",
:id => job.id,
- :type => JOB_LABELS[job.type_id],
+ :type => JOB_TYPES[job.type_id],
:url => seo_job_url(job)
}
end
respond_to do |format|
format.js { render :layout => false }
end
end
protected
def widget_from_params
@options = {
:width => "270px",
:background => "#FFFFFF",
:border => "#CCCCCC",
}.merge!(params)
end
end
diff --git a/app/helpers/application_helper.rb b/app/helpers/application_helper.rb
index 1d13077..ca9d62c 100644
--- a/app/helpers/application_helper.rb
+++ b/app/helpers/application_helper.rb
@@ -1,55 +1,55 @@
module ApplicationHelper
def collection_from_types(hash)
out = []
hash.each_with_index { |e,i| out << [e,i] }
return out
end
def stripped_params(o={})
p = params.clone
p.delete(:controller)
p.delete(:action)
p.delete(:page)
p.delete(:authenticity_token)
p.merge!(o)
return p
end
# add rss link
def rss_link(title, path)
tag :link, :type => 'application/rss+xml', :title => title, :href => path, :rel => "alternate"
end
def inline_errors(object, attribute)
errors = object.errors.on(attribute)
content_tag :p, errors.class == Array ? errors.join(', ') : errors, :class => 'inline-errors' unless errors.nil?
end
- def title_from_params(default="oferty pracy")
+ def title_from_params(default)
if default.class == Array
default = default.first
end
if @localization
- title = ["#{default} w ", @localization.name]
+ title = ["#{default} #{t('support.array.in_word_connector')} ", @localization.name]
elsif @framework
- title = ["#{default} dla ", @framework.name]
+ title = ["#{default} #{t('support.array.for_word_connector')} ", @framework.name]
elsif @type_id
- title = ["#{default} dla ", JOB_LABELS[@type_id]]
+ title = ["#{default} #{t('support.array.for_word_connector')} ", t("jobs.type.#{JOB_TYPES[@type_id]}")]
elsif @category
- title = ["#{default} w ", @category.name]
+ title = ["#{default} #{t('support.array.in_word_connector')} ", @category.name]
else
title = default.split(' ')
first = title.first
title.delete_at(0)
end
return [first,title]
end
- def render_title_from_params(default="ofery pracy")
+ def render_title_from_params(default)
title = title_from_params(default)
return content_tag(:span, title[0]) + ' ' + title[1].join(' ')
end
end
\ No newline at end of file
diff --git a/app/helpers/jobs_helper.rb b/app/helpers/jobs_helper.rb
index 40bb714..2c0a18c 100644
--- a/app/helpers/jobs_helper.rb
+++ b/app/helpers/jobs_helper.rb
@@ -1,25 +1,25 @@
module JobsHelper
def job_label(job)
html = ""
html += etykieta(job.type_id)
- html += content_tag :abbr, "Praca zdalna", :class => "etykieta zdalnie" if job.remote_job
+ html += content_tag :abbr, t("jobs.type.remote"), :class => "etykieta remote" if job.remote_job
return html
end
def etykieta(type_id)
- content_tag :abbr, JOB_LABELS[type_id], :class => "etykieta #{JOB_LABELS[type_id]}", :title => JOB_TYPES[type_id]
+ content_tag :abbr, t("jobs.type.#{JOB_TYPES[type_id]}"), :class => "etykieta #{JOB_TYPES[type_id]}", :title => t("jobs.type.#{JOB_TYPES[type_id]}")
end
def format_rank(rank)
((rank*10).round/10.0).to_s.gsub('.', ',')
end
def job_company(job)
if job.website.nil? || job.website.empty?
job.company_name
else
link_to job.company_name, job.website, :target => "_blank"
end
end
end
diff --git a/app/models/job.rb b/app/models/job.rb
index 63888ee..5273fe4 100644
--- a/app/models/job.rb
+++ b/app/models/job.rb
@@ -1,180 +1,178 @@
-JOB_TYPES = ["zlecenie (konkretna usÅuga do wykonania)", "poszukiwanie wspóÅpracowników / oferta pracy", "wolontariat (praca za reklamy, bannery, itp. lub praca za darmo)", "staż/praktyka"]
-JOB_LABELS = ["zlecenie", "etat", "wolontariat", "praktyka"]
-
+JOB_TYPES = ["freelance", "full_time", "free", "practice"]
JOB_ETAT = 1;
JOB_RANK_VALUES = {
:default => 0.3,
:price => 0.8,
:krs => 0.6,
:nip => 0.5,
:regon => 0.6,
:framework_id => 0.7,
:language_id => 0.7,
:website => 0.4,
:apply_online => 0.3
}
class Job < ActiveRecord::Base
include ActionController::UrlWriter
xss_terminate
has_permalink :title
named_scope :active, :conditions => ["((jobs.end_at >= ?) AND (jobs.published = ?))", Date.current, true]
named_scope :old, :conditions => ["jobs.end_at < ?", Date.current]
named_scope :has_text, lambda { |text| { :conditions => ["((jobs.title ILIKE ?) OR (jobs.description ILIKE ?))", "%#{text}%", "%#{text}%"] } }
validates_presence_of :title, :description, :email, :company_name, :localization_id, :category_id
validates_length_of :title, :within => 3..255
validates_length_of :description, :within => 10..5000
validates_inclusion_of :type_id, :in => 0..JOB_TYPES.size-1
validates_inclusion_of :availability_time, :in => 1..60
validates_numericality_of :price_from,
:greater_than => 0,
:unless => Proc.new { |j| j.price_from.nil? }
validates_numericality_of :price_to,
:greater_than => 0,
:unless => Proc.new { |j| j.price_to.nil? }
validates_format_of :email, :with => /([a-z0-9_.-]+)@([a-z0-9-]+)\.([a-z.]+)/i
validates_format_of :website, :with => /(^$)|(^(http|https):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(([0-9]{1,5})?\/.*)?$)/ix
validates_format_of :regon,
:with => /(^$)|(^[0-9]{7,14}$)/
validates_format_of :nip,
:with => /(^$)|(^\d{2,3}-\d{2,3}-\d{2,3}-\d{2,3}$)/
validates_format_of :krs,
:with => /(^$)|(^\d{10})$/
belongs_to :framework
belongs_to :localization
belongs_to :category
belongs_to :language
has_many :applicants, :dependent => :delete_all
has_many :visits, :dependent => :delete_all
attr_protected :rank, :permalink, :end_at, :token, :published
attr_accessor :framework_name, :localization_name
before_create :create_from_name, :generate_token
before_save :calculate_rank
after_create :send_notification
def self.find_grouped_by_type
return Job.active.count(:type_id, :group => "type_id")
end
def send_notification
JobMailer.deliver_job_posted(self)
end
def generate_token
alphanumerics = ('a'..'z').to_a.concat(('A'..'Z').to_a.concat(('0'..'9').to_a))
salt = alphanumerics.sort_by{rand}.to_s[0..1024]
self.token = Digest::SHA1.hexdigest("--#{salt}--#{self.id}--#{Date.current}--")
generate_token unless Job.find_by_token(self.token).nil?
end
def calculate_rank
self.rank = 1.0
self.rank += visits_count * 0.001 unless visits_count.nil?
self.rank += applicants_count * 0.01 unless applicants_count.nil?
[:regon, :nip, :krs, :framework_id, :website, :apply_online, :language_id].each do |attribute|
val = send(attribute)
inc = JOB_RANK_VALUES[attribute] || JOB_RANK_VALUES[:default]
self.rank += inc unless (val.nil? || (val.class == String && val.empty?) || (val.class == TrueClass))
end
if pay_band?
self.rank += JOB_RANK_VALUES[:price]
price = price_from || price_to
if price >= 10_000 # ciekawe czy ktoÅ da tyle :P
self.rank += 0.8
elsif price >= 7000
self.rank += 0.7
elsif price >= 5000
self.rank += 0.6
elsif price >= 3000
self.rank += 0.3
elsif price < 2000
if self.type_id == JOB_ETAT
self.rank -= 0.6 # bo nikt za grosze nie chce pracowaÄ
else
self.rank += 0.3 # chyba że to biedny student
end
end
end
end
def pay_band?
((!self.price_from.nil? && self.price_from > 0) || (!self.price_to.nil? && self.price_to > 0))
end
def create_from_name
unless (self.framework_name.nil? || self.framework_name.blank?)
framework = Framework.name_like(self.framework_name).first
framework = Framework.create(:name => self.framework_name) if framework.nil?
self.framework = framework
end
unless (self.localization_name.nil? || self.localization_name.blank?)
localization = Localization.name_like(self.localization_name).first
localization = Localization.create(:name => self.localization_name) if localization.nil?
self.localization = localization
end
end
def availability_time
date = created_at.nil? ? Date.current.to_date : created_at.to_date
return (read_attribute(:end_at) - date).to_i rescue 14
end
def availability_time=(val)
date = created_at.nil? ? Date.current.to_date : created_at.to_date
write_attribute(:end_at, date+val.to_i.days)
end
def highlighted?
self.rank >= 4.75
end
def publish!
self.published = true
save
spawn do
- tags = [localization.name, category.name, "praca", JOB_LABELS[self.type_id]]
+ tags = [localization.name, category.name, "praca", JOB_TYPE[self.type_id]]
tags << framework.name unless framework.nil?
tags << language.name unless language.nil?
MicroFeed.send :streams => :all,
:msg => "[#{company_name}] - #{title}",
:tags => tags,
:link => seo_job_url(self, :host => "webpraca.net") if Rails.env == "production"
end
end
def visited_by(ip)
visit = visits.find_or_create_by_ip(IPAddr.new(ip).to_i)
visits_count += 1 if visit.new_record?
save
end
def to_param
permalink
end
end
diff --git a/app/stylesheets/ui.less b/app/stylesheets/ui.less
index f4da3d9..7bc1440 100644
--- a/app/stylesheets/ui.less
+++ b/app/stylesheets/ui.less
@@ -1,602 +1,602 @@
/* Defaults */
@text_color: #393733;
@link_color: #31627E;
@hover_color: #FF5917;
/* Global */
body {
margin: 0;
padding: 0;
font: 12px Arial;
color: @text_color;
overflow: auto;
background: #76787B url('/images/bkg.png') repeat-x top;
}
h1, h2, h3, h4 { margin: 0 0 5px 0; }
a { color: @link_color; cursor: pointer; outline: none !important; text-decoration: none; }
a:hover, a:focus { color: @hover_color; }
a img { border: 0; }
/* Table */
table { border-collapse: collapse; width: 100%; }
td, th {
font-size:11px;
border-bottom:1px solid #eee;
padding:5px;
}
th { text-align:left; font-size:12px; }
thead th { font-weight:bold; color:#666; padding:2px 5px; font-size:11px; background:#e1e1e1 url(/images/nav-bg.gif) top left repeat-x; border-left:1px solid #ddd; border-bottom:1px solid #ddd; }
thead th:first-child { border-left:none !important; }
thead th.optional { font-weight:normal !important; }
tr.alt { background:#f6f6f6; }
/* IDS */
.prices input[type="text"] { width: 50px !important; text-align: right; }
#job_captcha_image, #applicant_captcha_image, .captcha img { margin-bottom: -22px !important; margin-right: 10px !important; }
#job_captcha_solution, #applicant_captcha_solution, .captcha input { width: 200px !important; }
#AdTaily_Widget_Container { padding-top: 5px; }
/* Custom class */
.rounded_corners (@radius: 5px) {
-moz-border-radius: @radius;
-webkit-border-radius: @radius;
border-radius: @radius;
-o-border-radius: @radius;
}
.rounded_corner_top_left(@radius: 5px) { -moz-border-radius-topleft: @radius; -webkit-border-top-left-radius: @radius; border-top-left-radius: @radius; }
.rounded_corner_top_right(@radius: 5px) { -moz-border-radius-topright: @radius; -webkit-border-top-right-radius: @radius; border-top-right-radius: @radius; }
.rounded_corner_bottom_left(@radius: 5px) { -moz-border-radius-bottomleft: @radius; -webkit-border-bottom-left-radius: @radius; border-bottom-left-radius: @radius; }
.rounded_corner_bottom_right(@radius: 5px) { -moz-border-radius-bottomright: @radius; -webkit-border-bottom-right-radius: @radius; border-bottom-right-radius: @radius; }
.reset { margin: 0; padding: 0; list-style: none; }
.text_center { text-align: center; }
.text_right { text-align: right; }
.clear { clear: both; }
.info { text-align: center; color: #ddd; font-size: 28px; font-weight: bold; }
.loader { background: transparent url('/images/ajax.gif') no-repeat center center; height: 20px; display: none; }
.right { float: right; }
.left { float: left; }
/* Flash */
.flash {
background-color: #A4E1A2;
border: 1px solid #DDE3D7;
text-shadow: #C0FDE3 0px 1px 0px;
.rounded_corners(5px);
color: #094808;
margin-top: 10px;
opacity: 0.8;
padding: 10px;
}
.flash.error {
background-color: #AF2B2B;
color: #fff;
border: 1px solid #DA3536;
text-shadow: #000 0px 1px 0px;
}
.flash:hover { opacity: 1.0; }
.flash .dismiss {
background: transparent url('/images/close.png') no-repeat !important;
float: right;
height: 10px;
width: 9px;
text-indent: 9999px;
overflow: hidden;
}
.flash p {
font-weight: normal;
line-height: 15px;
margin: 0px;
}
.flash_error {
background: #AF2B2B url('../images/icon-error.png') 20px center no-repeat;
color: #fff;
border: 1px solid #DA3536;
text-shadow: #000 0px 1px 0px;
}
/* Buttons */
.buttons { margin: 0 5px; }
.button {
background: #DDD url('../images/button.png') repeat-x 0px 0px;
border: 1px solid #999;
display: inline-block;
outline: none;
-webkit-box-shadow: rgba(0, 0, 0, 0.117188) 0px 1px 0px;
}
.button > input[type="button"], .button > input[type="submit"], .button > a {
border: none;
line-height: 23px;
height: 23px;
padding: 0 10px;
color: #333 !important;
font-weight: bold;
text-decoration: none;
font-size: 11px;
cursor: default;
background: transparent;
}
.button:active {
background-color: #ddd;
background-image: none;
}
.button img {
margin-bottom: -4px;
margin-right: 5px;
width: 16px;
height: 16px;
}
.button.right { float: right; }
/* TextFields */
select { min-width: 150px; }
input[type="text"], input[type="password"], textarea {
padding: 4px 3px !important;
border: 1px solid #96A6C5;
color: #000;
}
textarea { height: 200px; min-height: 200px; }
input[type="text"]:focus, input[type="password"]:focus, textarea:focus {
background-color: #e6f7ff;
border-bottom: 1px solid #7FAEFF;
border-right: 1px solid #7FAEFF;
border-left: 1px solid #4478A8;
border-top: 1px solid #4478A8;
}
form > fieldset {
border: 2px solid #ddd !important;
.rounded_corners;
padding: 10px 15px !important;
margin: 10px 5px !important;
}
form > fieldset > legend {
font-weight: bold;
padding: 0 15px 0px 0 !important;
margin-left: -22px !important;
background: #fff;
font-size: 16px;
color: #333 !important;
}
/* Wrapper */
@wrapper_width: 900px;
.wrapper {
margin: 0px auto;
width: @wrapper_width;
min-height: 500px;
}
/* Header */
@header_height: 80px;
.wrapper > .header {
height: @header_height;
width: @wrapper_width;
position:relative;
}
@logo_width: 347px;
@menu_color: #35373A;
@header_link_color: #D8D8D9;
.header > h1#logo {
left: 8px;
position: absolute;
top: 10px;
width: @logo_width;
}
.header > h1#logo a { color: #fff; font: 28px "Trebuchet MS"; font-weight: bold; }
.header > h1#logo a:hover { background: transparent; }
.header > ul.categories {
.reset;
position: absolute;
bottom: 5px;
left: 0px;
width: @content_width;
}
.header > ul.categories li {
display:inline;
margin-left: 3px;
}
.header > ul.categories li.right { float: right; margin-left: 6px; }
.header > ul.categories li > a {
padding: 5px 10px;
margin-top: 5px;
font-size: 13px;
color: @header_link_color;
.rounded_corner_top_left;
.rounded_corner_top_right;
background: @menu_color;
}
.header > ul.categories li > a:hover { background: #5d5f62; }
.header > ul.categories li > .selected { color: #fff; background: #2A2B2D !important; }
.header > ul.menu {
.reset;
.rounded_corner_bottom_left;
.rounded_corner_bottom_right;
position:absolute;
top: 0px;
padding: 5px 10px;
right: 0px;
background: @menu_color;
}
.header > ul.menu li{
display:inline;
margin-left: 3px;
padding-left: 6px;
border-left: 1px dotted #212326;
background-color:transparent;
font-size: 10px;
font-weight: bold;
color: @header_link_color;
}
.header > ul.menu li a { color: @header_link_color; }
.header > ul.menu li a:hover { color: #fff; background: transparent; }
.header > ul.menu li:first-child { border: 0; margin-left: 0; padding-left: 0; }
/* Sidebar */
@sidebar_width: 200px;
.wrapper > .sidebar {
float: right;
width: @sidebar_width;
margin-top: 20px;
}
.wrapper > .sidebar ul { .reset; }
/* content */
@content_padding_right: 10px;
@content_width: @wrapper_width - @sidebar_width - @content_padding_right;
.wrapper > .content {
float: left;
width: @content_width;
padding-right: @content_padding_right;
margin-top: 20px;
}
/*.wrapper > .content p { margin: 0 0 10px 0; padding: 0;} */
/* Box */
.box {
margin-bottom: 10px;
padding: 6px;
background: #9C9C9C;
.rounded_corners(5px);
}
@box_div_border_radius: 4px;
.box > div {
background: #fff;
margin-bottom: 10px;
padding-bottom: 5px;
.rounded_corners(@box_div_border_radius);
}
.box > div > .text { margin: 10px; }
.box > div > .text p { margin: 10px 0; }
.box > div:last-child { margin-bottom: 0; }
@title_height: 39px;
@sidebar_title_height: 29px;
.box .title {
height: @title_height;
.rounded_corner_top_right(@box_div_border_radius);
.rounded_corner_top_left(@box_div_border_radius);
display: block;
background: #fff url('/images/title-header.png') repeat-x bottom;
border-bottom: 1px solid #F1EFBD;
}
.box .title > h2, .box .title > h3 {
margin: 0;
padding: 1px 10px 0 10px;
line-height: @title_height - 1px;
font-weight: normal;
font-size: 18px;
color: #656666;
}
.box .title > h3 {
font-size: 16px;
line-height: @sidebar_title_height - 1px;
}
.box .title > h2 > span, .box .title > h3 > span { color: #8E8F8F; }
.box > div form { margin: 5px !important; }
.box p {
margin: 10px;
}
.sidebar .box .title, .box .title.mini {
height: @sidebar_title_height;
}
/* list */
.list {
.reset;
.clear;
}
.list > li { clear: both; padding: 5px; }
.list > .alt { background:#f6f6f6; }
.list > li > .ranked { font-weight: bold; }
.list > li .handle { cursor: move; margin: 3px 5px 0 5px; }
.list > li > .badge {
float: right;
min-width: 18px;
padding: 2px 3px;
font-weight: bold;
font-size: 10px;
color: #fff;
background: #8798BB;
.rounded_corners(7px);
text-align: center;
}
.list > li > .rank {
.rounded_corners(2px);
text-align: center;
min-width: 18px;
padding: 2px 3px;
font-weight: bold;
font-size: 9px;
float: right;
background: #FFFF98;
border: 1px solid #E2E28C;
margin-top: -1px;
}
.list > li > .date {
font-size: 11px;
font-style: italic;
color: #7C7C7C;
}
/* more button */
.more {
background: #fff url('/images/more.gif') 0% 0% repeat-x;
border: 1px solid #DDD;
border-bottom: 1px solid #AAA;
border-right: 1px solid #AAA;
display: block;
font-size: 14px;
font-weight: bold;
color: inherit;
height: 22px;
line-height: 1.5em;
padding: 6px 0px;
text-align: center;
text-shadow: #fff 1px 1px 1px;
.rounded_corners(6px);
}
.more:hover {
background-position: 0% -78px;
border: 1px solid #BBB;
color: inherit;
}
.more:active {
background-position: 0% -38px;
color: #666;
}
/* Etykiety */
.etykieta {
display: block;
float: left;
font-size: 9px;
margin-right: 5px;
margin-top: -1px;
text-align: center;
width: 60px;
.rounded_corners(2px);
padding: 2px 3px;
color: #fff;
}
.etykieta:hover { color: #fff; }
-.etykieta.zdalnie {
+.etykieta.remote {
background: #357CCB;
border: 1px solid #2C6AB0;
}
-.etykieta.zlecenie {
+.etykieta.freelance {
background: #F8854E;
border: 1px solid #D27244;
}
-.etykieta.etat {
+.etykieta.full_time {
background: #408000;
border: 1px solid #366E01;
}
-.etykieta.praktyka {
+.etykieta.practice {
background: #FF6;
border: 1px solid #E2E25C;
color: #31627E;
}
.praktyka:hover { color: #31627E; }
-.etykieta.wolontariat {
+.etykieta.free {
background: #D6D6D6;
border: 1px solid #B1B1B1;
color: #31627E;
}
.wolontariat:hover { color: #31627E; }
/* Pagination */
.pagination { background: white; margin: 5px 5px 0 5px; }
.pagination a, .pagination span {
padding: .2em .5em;
display: block;
float: left;
margin-right: 1px;
}
.pagination span.disabled {
color: #999;
border: 1px solid #DDD;
}
.pagination span.current {
font-weight: bold;
background: #2E6AB1;
color: white;
border: 1px solid #2E6AB1;
}
.pagination a {
text-decoration: none;
color: #105CB6;
border: 1px solid #9AAFE5;
}
.pagination a:hover, .pagination a:focus {
color: #003;
border-color: #003;
background-color: transparent;
}
.pagination .page_info {
background: #2E6AB1;
color: white;
padding: .4em .6em;
width: 22em;
margin-bottom: .3em;
text-align: center;
}
.pagination .page_info b {
color: #003;
background: #6aa6ed;
padding: .1em .25em;
}
.pagination:after {
content: ".";
display: block;
height: 0;
clear: both;
visibility: hidden;
}
* html .pagination { height: 1%; }
*:first-child+html .pagination { overflow: hidden; }
/* describe list */
@dt_width: 180px;
@dt_padding_right: 10px;
@dl_padding_left: 10px;
dl {
padding: 0px;
margin: 10px 0 0 0;
display: block;
}
dl dt {
width: @dt_width;
text-align: right;
color: #888;
float: left;
display: block;
padding: 0 @dt_padding_right 6px 0;
margin: 0;
}
dl dd {
width: @content_width - @dt_width - @dt_padding_right - @dl_padding_left - 15px;
border-left: 1px solid #ccc;
float: left;
padding: 0 0 10px @dl_padding_left;
margin: 0;
}
dl dd:last-child { padding-bottom: 0px; }
dl dd ul {
padding: 5px 0 0 20px;
margin: 0;
}
/* feed icon */
.feed {
float: right;
margin-top: 5px;
margin-right: -3px;
}
/* footer */
.footer {
margin: 10px auto;
width: @wrapper_width;
color: #D8D8D9;
}
.footer strong a { color: #fff; }
.footer a { color: #D8D8D9; }
.footer a:hover { color: #fff; }
.footer .right { margin-top: 3px; }
\ No newline at end of file
diff --git a/app/views/jobs/_jobs.html.erb b/app/views/jobs/_jobs.html.erb
index 8111cec..0badf79 100644
--- a/app/views/jobs/_jobs.html.erb
+++ b/app/views/jobs/_jobs.html.erb
@@ -1,17 +1,17 @@
<% if jobs.nil? || jobs.empty? %>
<p class="info">Brak ofert</p>
<% else %>
<ul class="list">
<% jobs.each do |job| %>
<li class="<%= cycle('normal', 'alt') %>">
<span class="rank"><%= format_rank(job.rank) %></span>
<%= job_label(job) %>
- <%= link_to job.title, seo_job_path(job), :class => job.highlighted? ? 'ranked' : nil %> dla <%= job_company(job) %> / <%= link_to job.localization.name, localization_path(job.localization) %>
+ <%= link_to job.title, seo_job_path(job), :class => job.highlighted? ? 'ranked' : nil %><%= t('support.array.for_word_connector') %><%= job_company(job) %> / <%= link_to job.localization.name, localization_path(job.localization) %>
<abbr class="date" title="<%= job.created_at.xmlschema %>">
- <%= distance_of_time_in_words_to_now job.created_at %> temu
+ <%= distance_of_time_in_words_to_now job.created_at %> <%= t('datetime.distance_in_words.ago') %>
</abbr>
</li>
<% end %>
</ul>
<%= will_paginate jobs if jobs.respond_to?(:total_pages) %>
<% end %>
\ No newline at end of file
diff --git a/app/views/jobs/_sidebar.html.erb b/app/views/jobs/_sidebar.html.erb
index 6f79d28..35e4267 100644
--- a/app/views/jobs/_sidebar.html.erb
+++ b/app/views/jobs/_sidebar.html.erb
@@ -1,56 +1,56 @@
<div class="box">
<div>
- <div class="title"><h3>typ</h3></div>
+ <div class="title"><h3><%= t('layout.sidebar.type') %></h3></div>
<ul class="list">
<% Job.find_grouped_by_type.each do | type_id, jobs_count | %>
<li class="<%= cycle('normal', 'alt') %>">
<span class="badge"><%= jobs_count %></span>
- <%= link_to JOB_LABELS[type_id], job_type_path(JOB_LABELS[type_id]) , :class => "etykieta #{JOB_LABELS[type_id]}"%>
+ <%= link_to t("jobs.type.#{JOB_TYPES[type_id]}"), job_type_path(JOB_TYPES[type_id]) , :class => "etykieta #{JOB_TYPES[type_id]}"%>
</li>
<% end %>
</ul>
<div class="clear"></div>
</div>
<div>
<div class="title">
- <h3>lokalizacje</h3>
+ <h3><%= t('layout.sidebar.localization') %></h3>
</div>
<ul class="list">
<% for place in Localization.find_job_localizations %>
<li class="<%= cycle('normal', 'alt') %>">
<span class="badge"><%= place.jobs_count %></span>
<%= link_to place.name, localization_path(place.permalink) %>
</li>
<% end %>
</ul>
</div>
<div>
<div class="title">
- <h3>jÄzyk</h3>
+ <h3><%= t('layout.sidebar.language') %></h3>
</div>
<ul class="list">
<% for language in Language.find_job_languages %>
<li class="<%= cycle('normal', 'alt') %>">
<span class="badge"><%= language.jobs_count %></span>
<%= link_to language.name, language_path(language) %>
</li>
<% end %>
</ul>
</div>
<div>
<div class="title">
- <h3>frameworki</h3>
+ <h3><%= t('layout.sidebar.frameworks') %></h3>
</div>
<ul class="list">
<% for framework in Framework.find_job_frameworks %>
<li class="<%= cycle('normal', 'alt') %>">
<span class="badge"><%= framework.jobs_count %></span>
<%= link_to framework.name, framework_path(framework.permalink) %>
</li>
<% end %>
</ul>
</div>
</div>
diff --git a/app/views/jobs/home.html.erb b/app/views/jobs/home.html.erb
index 7732b93..0d06d6b 100644
--- a/app/views/jobs/home.html.erb
+++ b/app/views/jobs/home.html.erb
@@ -1,32 +1,32 @@
<% content_for :sidebar do %>
<%= render :partial => "/jobs/sidebar" %>
<% end %>
<div class="box">
<div>
<div class="title">
<h2>
- <%= link_to image_tag('feed.png'), jobs_path(stripped_params(:format => :rss, :order => "najpopularniejsze")), :title => "najpopularniejsze", :class => "feed" %>
- <span>najpopularniejsze</span> oferty
+ <%= link_to image_tag('feed.png'), jobs_path(stripped_params(:format => :rss, :order => "najpopularniejsze")), :title => t('home.popular'), :class => "feed" %>
+ <span><%= t('home.popular') %></span> <%= t 'home.jobs' %>
</h2>
</div>
<%= render :partial => "jobs", :object => @top_jobs %>
</div>
<div>
<%= render :partial => "/shared/ads" %>
</div>
<div>
<div class="title">
<h2>
- <%= link_to image_tag('feed.png'), jobs_url(stripped_params(:format => :rss)), :title => "najnowsze oferty", :class => "feed" %>
- <span>najnowsze</span> oferty
+ <%= link_to image_tag('feed.png'), jobs_url(stripped_params(:format => :rss)), :title => t('home.latest'), :class => "feed" %>
+ <span><%= t 'home.latest' %></span> <%= t 'home.jobs' %>
</h2>
</div>
<%= render :partial => "jobs", :object => @recent_jobs %>
</div>
- <%= link_to 'pokaż wiÄcej ofert', jobs_path, :class => "more" %>
+ <%= link_to t('home.more_jobs'), jobs_path, :class => "more" %>
</div>
\ No newline at end of file
diff --git a/app/views/jobs/index.atom.builder b/app/views/jobs/index.atom.builder
index 800b32f..3228bcf 100644
--- a/app/views/jobs/index.atom.builder
+++ b/app/views/jobs/index.atom.builder
@@ -1,13 +1,13 @@
atom_feed do |feed|
feed.title(@page_title.join(' | '))
unless @jobs.empty?
feed.updated((@jobs.first.created_at))
end
@jobs.each do |job|
feed.entry(job) do |entry|
- entry.title("[#{JOB_LABELS[job.type_id]}] #{job.title}")
+ entry.title("[#{JOB_TYPES[job.type_id]}] #{job.title}")
entry.content(truncate(job.description, :length => 512), :type => 'html')
end
end
end
\ No newline at end of file
diff --git a/app/views/jobs/index.rss.builder b/app/views/jobs/index.rss.builder
index 0d02061..6453b5f 100644
--- a/app/views/jobs/index.rss.builder
+++ b/app/views/jobs/index.rss.builder
@@ -1,19 +1,19 @@
xml.instruct! :xml, :version => "1.0"
xml.rss :version => "2.0" do
xml.channel do
xml.title @page_title.join(' | ')
xml.link jobs_url(stripped_params(:format => :html))
for job in @jobs
xml.item do
- xml.title "[#{JOB_LABELS[job.type_id]}] #{job.title}"
+ xml.title "[#{JOB_TYPES[job.type_id]}] #{job.title}"
xml.description truncate(job.description, :length => 512)
xml.pubDate job.created_at.to_s(:rfc822)
xml.link seo_job_url(job)
xml.guid job_url(job)
end
end
end
end
\ No newline at end of file
diff --git a/app/views/jobs/search.html.erb b/app/views/jobs/search.html.erb
index 7eb277a..ff20121 100644
--- a/app/views/jobs/search.html.erb
+++ b/app/views/jobs/search.html.erb
@@ -1,43 +1,43 @@
<% content_for :sidebar do %>
<%= render :partial => "/jobs/sidebar" %>
<% end %>
<% unless (@jobs.nil? || @jobs.empty?) %>
<div class="box">
<div>
<div class="title">
<h2>
<%= link_to image_tag('feed.png'), search_jobs_url(stripped_params(:format => :rss)), :title => "Subskrybuj wyszukiwanie", :class => "feed" %>
Wyniki dla <span>wyszukiwania</span>
</h2>
</div>
<%= render :partial => "jobs", :object => @jobs %>
</div>
</div>
<% end %>
<div class="box">
<div>
<div class="title">
<h2><span>Szukaj</span> oferty</h2>
</div>
<% semantic_form_for @search, :url => search_jobs_path, :html => { :method => :post } do |f| %>
<% f.inputs :name => "Wyszukiwarka" do %>
<%= f.input :has_text, :required => false, :label => "ZawierajÄ
cy tekst" %>
<%= f.input :category_id_equals, :required => false, :as => :check_boxes, :collection => Category.all.map { |category| [category.name, category.id] }, :wrapper_html => { :class => "columns" }, :label => "Kategorie" %>
- <%= f.input :type_id_equals, :required => false, :as => :check_boxes, :collection => collection_from_types(JOB_LABELS), :label => "Typ" %>
+ <%= f.input :type_id_equals, :required => false, :as => :check_boxes, :collection => collection_from_types(JOB_TYPES), :label => "Typ" %>
<%= f.input :localization_id_equals, :required => false, :as => :check_boxes, :collection => Localization.all.map { |l| [l.name, l.id] }, :wrapper_html => { :class => "columns" }, :label => "Lokalizacja" %>
<%= f.input :framework_id_equals, :required => false, :as => :check_boxes, :collection => Framework.all.map { |frame| [frame.name, frame.id] }, :wrapper_html => { :class => "columns" }, :label => "Używane frameworki" %>
<li class="numeric prices">
<label>WideÅki zarobkowe:</label>
<%= f.text_field :price_from_greater_than_or_equal_to %> do <%= f.text_field :price_to_less_than_or_equal_to %> PLN
</li>
<% end %>
<div class="buttons">
<div class="button"><%= f.submit "Szukaj!" %></div>
</div>
<% end %>
</div>
</div>
diff --git a/app/views/layouts/application.html.erb b/app/views/layouts/application.html.erb
index ed659e2..87c1a2a 100644
--- a/app/views/layouts/application.html.erb
+++ b/app/views/layouts/application.html.erb
@@ -1,92 +1,91 @@
<!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" lang="pl">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="google-site-verification" content="zE20xzrx6CCNbFsmsNTok9xaPavS0Cmu7hJxdUbNqN8" />
<%= display_meta_tags :site => WebSiteConfig['website']['name'] %>
<meta name="viewport" content="width=900" />
<%= rss_link("RSS", jobs_url(:format => :rss)) %>
<%= rss_link("ATOM", jobs_url(:format => :atom)) %>
<%= javascript_tag "window._token = '#{form_authenticity_token}'" %>
<%= javascript_include_merged :base %>
<%= stylesheet_link_merged :base %>
</head>
<body>
<div class="wrapper">
<div class="header">
<h1 id="logo"><%= link_to WebSiteConfig['website']['name'], root_path %></h1>
<ul class="categories">
<li class="right">
- <%= link_to "Najpopularniejsze", seo_jobs_path(:order => 'najpopularniejsze', :category => params[:category]), :class => (!@order.nil? && @order == :rank) ? "selected" : "normal" %>
+ <%= link_to t('layout.popular'), seo_jobs_path(:order => 'najpopularniejsze', :category => params[:category]), :class => (!@order.nil? && @order == :rank) ? "selected" : "normal" %>
</li>
<li class="right">
- <%= link_to "Najnowsze", seo_jobs_path(:order => 'najnowsze', :category => params[:category] ), :class => (!@order.nil? && @order == :created_at) ? "selected" : "normal" %>
+ <%= link_to t('layout.latest'), seo_jobs_path(:order => 'najnowsze', :category => params[:category] ), :class => (!@order.nil? && @order == :created_at) ? "selected" : "normal" %>
</li>
<% for category in Category.all(:order => "position") %>
<li>
<%= link_to category.name, seo_jobs_path(:order => params[:order], :category => category.permalink), :class => (!@category.nil? && @category.id == category.id) ? "selected" : "normal" %>
</li>
<% end %>
</ul>
<ul class="menu">
- <li><%= link_to "Strona gÅówna", root_path %></li>
- <li><%= link_to "Szukaj", search_jobs_path %></li>
- <li><%= link_to "Informacje", "/strona/informacje/" %></li>
- <li><%= link_to "Regulamin", "/strona/regulamin/" %></li>
- <li><%= link_to "Obserwuj nas", "/strona/obserwuj-nas" %></li>
- <li><%= link_to "Kontakt", contact_path %></li>
- <li><%= link_to "Gadżet na stronÄ", new_widget_path %></li>
+ <li><%= link_to t('layout.menu.main'), root_path %></li>
+ <li><%= link_to t('layout.menu.search'), search_jobs_path %></li>
+ <li><%= link_to t('layout.menu.about'), "/strona/informacje/" %></li>
+ <li><%= link_to t('layout.menu.terms'), "/strona/regulamin/" %></li>
+ <li><%= link_to t('layout.menu.follow'), "/strona/obserwuj-nas" %></li>
+ <li><%= link_to t('layout.menu.contact'), contact_path %></li>
</ul>
</div>
<%- flash.each do |name, msg| -%>
<div class="<%= "flash #{name}" %>">
<a href="#" class="dismiss">X</a>
<p><%= msg %></p>
</div>
<%- end -%>
<div class="sidebar">
<div class="box">
- <%= link_to "Dodaj ofertÄ za DARMO!", new_job_path, :id => "add_job", :class => "more", :rel => "nofollow" %>
+ <%= link_to t('layout.sidebar.post_job'), new_job_path, :id => "add_job", :class => "more", :rel => "nofollow" %>
</div>
<%= yield :sidebar %>
<% if @ads_pos == :right %>
<div class="box">
<div>
<%= render :partial => "/shared/ads" %>
</div>
</div>
<% end %>
</div>
<div class="content">
<%= yield %>
<% if @ads_pos == :bottom %>
<div class="box">
<div>
<%= render :partial => "/shared/ads" %>
</div>
</div>
<% end %>
</div>
<div class="clear"></div>
</div>
<%= render :partial => "/shared/footer" %>
<script type="text/javascript" src="http://flaker.pl/track/site/1122612"></script>
<script type="text/javascript" src="http://app.sugester.pl/webpraca/widget.js"></script>
<script type="text/javascript">
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script>
<script type="text/javascript">
try {
var pageTracker = _gat._getTracker("UA-11469054-5");
pageTracker._trackPageview();
} catch(err) {}</script>
</body>
</html>
\ No newline at end of file
diff --git a/app/views/shared/_footer.html.erb b/app/views/shared/_footer.html.erb
index 394cb5d..0f2a5b1 100644
--- a/app/views/shared/_footer.html.erb
+++ b/app/views/shared/_footer.html.erb
@@ -1,12 +1,12 @@
<div class="footer">
<span class="right">
- <%= link_to "Strona gÅówna", root_path %> |
- <%= link_to "Oferty", jobs_path %> |
- <%= link_to "Szukaj", search_jobs_path %> |
- <%= link_to "Informacje", "/strona/informacje/" %> |
- <%= link_to "Regulamin", "/strona/regulamin/" %> |
- <%= link_to "Kontakt", contact_path %> |
+ <%= link_to t('layout.menu.main'), root_path %> |
+ <%= link_to t('layout.menu.search'), search_jobs_path %> |
+ <%= link_to t('layout.menu.about'), "/strona/informacje/" %> |
+ <%= link_to t('layout.menu.terms'), "/strona/regulamin/" %> |
+ <%= link_to t('layout.menu.follow'), "/strona/obserwuj-nas" %> |
+ <%= link_to t('layout.menu.contact'), contact_path %> |
<%= link_to "GitHub", "http://github.com/macbury/webpraca" %>
</span>
<strong><%= link_to WebSiteConfig['website']['name'], root_path %></strong> <sup>BETA</sup> © <%= Date.current.year %>.
</div>
\ No newline at end of file
diff --git a/config/locales/pl.yml b/config/locales/pl.yml
index 583a439..9ceed90 100644
--- a/config/locales/pl.yml
+++ b/config/locales/pl.yml
@@ -1,176 +1,225 @@
# Polish translations for Ruby on Rails
# by Jacek Becela (jacek.becela@gmail.com, http://github.com/ncr)
pl:
+ flash:
+ notice:
+ email_verification: "Na twój e-mail zostaÅ wysÅany link którym opublikujesz ofertÄ."
+ job_updated: "Zapisano zmiany w ofercie."
+ job_published: "Twoja oferta jest już widoczna!"
+ job_deleted: "Oferta zostaÅa usuniÄta"
+ title:
+ popular: "najpopularniejsze oferty pracy IT"
+ latest: "najnowsze oferty pracy IT"
+ search: "Szukaj oferty"
+ finded_jobs: "Znalezione oferty"
+ jobs: "Oferty pracy IT"
+ jobs:
+ type:
+ full_time: "etat"
+ freelance: "zlecenie"
+ free: "wolontariat"
+ practice: "praktyka"
+ remote: "praca zdalna"
+ type_long:
+ full_time: "poszukiwanie wspóÅpracowników / oferta pracy"
+ freelance: "zlecenie (konkretna usÅuga do wykonania)"
+ free: "wolontariat (praca za reklamy, bannery, itp. lub praca za darmo)"
+ practice: "staż/praktyka"
+ layout:
+ popular: "Najpopularniejsze"
+ latest: "Najnowsze"
+ menu:
+ main: "Strona gÅówna"
+ search: "Szukaj"
+ about: "O serwisie"
+ terms: "Regulamin"
+ follow: "Obserwuj nas"
+ contact: "Kontakt"
+ sidebar:
+ post_job: "Dodaj ofertÄ za DARMO!"
+ type: "typ"
+ localization: "lokalizacje"
+ language: "jÄzyk"
+ frameworks: "framework"
+ home:
+ title: "najpopularniejsze i najnowsze oferty pracy z IT"
+ popular: "Najpopularniejsze"
+ latest: "Najnowsze"
+ jobs: "oferty"
+ more_jobs: "pokaż wiÄcej ofert"
number:
format:
separator: ","
delimiter: " "
precision: 2
currency:
format:
format: "%n %u"
unit: "PLN"
percentage:
format:
delimiter: ""
precision:
format:
delimiter: ""
human:
format:
delimiter: ""
precision: 1
storage_units:
format: "%n %u"
units:
byte:
one: "bajt"
other: "bajty"
kb: "KB"
mb: "MB"
gb: "GB"
tb: "TB"
date:
formats:
default: "%Y-%m-%d"
short: "%d %b"
school: "%Y"
simple: "%d.%m.%Y"
long: "%d %B %Y"
day_names: [Niedziela, PoniedziaÅek, Wtorek, Åroda, Czwartek, PiÄ
tek, Sobota]
abbr_day_names: [nie, pon, wto, Åro, czw, pia, sob]
month_names: [~, StyczeÅ, Luty, Marzec, KwiecieÅ, Maj, Czerwiec, Lipiec, SierpieÅ, WrzesieÅ, Październik, Listopad, GrudzieÅ]
abbr_month_names: [~, sty, lut, mar, kwi, maj, cze, lip, sie, wrz, paź, lis, gru]
order: [ :year, :month, :day ]
time:
formats:
default: "%a, %d %b %Y, %H:%M:%S %z"
short: "%d %b, %H:%M"
long: "%d %B %Y, %H:%M"
am: "przed poÅudniem"
pm: "po poÅudniu"
datetime:
distance_in_words:
+ ago: "temu"
half_a_minute: "póŠminuty"
less_than_x_seconds:
one: "mniej niż sekundÄ"
few: "mniej niż {{count}} sekundy"
other: "mniej niż {{count}} sekund"
x_seconds:
one: "sekundÄ"
few: "{{count}} sekundy"
other: "{{count}} sekund"
less_than_x_minutes:
one: "mniej niż minutÄ"
few: "mniej niż {{count}} minuty"
other: "mniej niż {{count}} minut"
x_minutes:
one: "minutÄ"
few: "{{count}} minuty"
other: "{{count}} minut"
about_x_hours:
one: "okoÅo godziny"
other: "okoÅo {{count}} godzin"
x_days:
one: "1 dzieÅ"
other: "{{count}} dni"
about_x_months:
one: "okoÅo miesiÄ
ca"
other: "okoÅo {{count}} miesiÄcy"
x_months:
one: "1 miesiÄ
c"
few: "{{count}} miesiÄ
ce"
other: "{{count}} miesiÄcy"
about_x_years:
one: "okoÅo roku"
other: "okoÅo {{count}} lat"
over_x_years:
one: "ponad rok"
few: "ponad {{count}} lata"
other: "ponad {{count}} lat"
activerecord:
models:
user: "Użytkownik"
job: "Praca"
search: "Wyszukiwarka"
applicant: "Aplikant"
comment:
attributes:
captcha_solution:
blank: 'musi byÄ podane'
invalid: 'odpowiedź jest niepoprawna'
attributes:
websiteconfig:
groups:
website: "Strona WWW"
js: "Skrypty"
js:
google_analytics: "Google Analytics"
widget: "Reklama"
website:
name: "Nazwa"
tags: "SÅowa kluczowe"
description: "Opis"
applicant:
email: "Twój E-Mail"
body: "TreÅÄ"
cv: "Dodaj ofertÄ/CV"
job:
title: "TytuÅ"
place_id: "Lokalizacja"
description: "Opis"
availability_time: "DÅugoÅÄ trwania"
remote_job: "Praca zdalna"
type_id: "Typ"
category_id: "Kategoria"
company_name: "Nazwa"
website: "Strona WWW"
framework_name: "Framework"
apply_online: "Aplikuj online"
email_title: "TytuÅ emaila"
language: "JÄzyk"
user:
password: "HasÅo"
password_confirmation: "Powtórz hasÅo"
errors:
template:
header:
one: "{{model}} nie zostaÅ zachowany z powodu jednego bÅÄdu"
other: "{{model}} nie zostaÅ zachowany z powodu {{count}} bÅÄdów"
body: "BÅÄdy dotyczÄ
nastÄpujÄ
cych pól:"
messages:
inclusion: "nie znajduje siÄ na liÅcie dopuszczalnych wartoÅci"
exclusion: "znajduje siÄ na liÅcie zabronionych wartoÅci"
invalid: "jest nieprawidÅowe"
confirmation: "nie zgadza siÄ z potwierdzeniem"
accepted: "musi byÄ zaakceptowane"
empty: "nie może byÄ puste"
blank: "nie może byÄ puste"
too_long: "jest za dÅugie (maksymalnie {{count}} znaków)"
too_short: "jest za krótkie (minimalnie {{count}} znaków)"
wrong_length: "jest nieprawidÅowej dÅugoÅci (powinna wynosiÄ {{count}} znaków)"
taken: "zostaÅo już zajÄte"
not_a_number: "nie jest liczbÄ
"
greater_than: "musi byÄ wiÄksze niż {{count}}"
greater_than_or_equal_to: "musi byÄ wiÄksze lub równe {{count}}"
equal_to: "musi byÄ równe {{count}}"
less_than: "musi byÄ mniejsze niż {{count}}"
less_than_or_equal_to: "musi byÄ mniejsze lub równe {{count}}"
odd: "musi byÄ nieparzyste"
even: "musi byÄ parzyste"
record_invalid: "nieprawidÅowe dane"
support:
array:
sentence_connector: "i"
skip_last_comma: true
words_connector: ", "
two_words_connector: " i "
last_word_connector: " oraz "
+ for_word_connector: " dla "
+ in_word_connector: " w "
diff --git a/db/schema.rb b/db/schema.rb
index ffdd342..434b0b8 100644
--- a/db/schema.rb
+++ b/db/schema.rb
@@ -1,141 +1,135 @@
# This file is auto-generated from the current state of the database. Instead of editing this file,
# please use the migrations feature of Active Record to incrementally modify your database, and
# then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your database schema. If you need
# to create the application database on another system, you should be using db:schema:load, not running
# all the migrations from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended to check this file into your version control system.
ActiveRecord::Schema.define(:version => 20100109211453) do
create_table "applicants", :force => true do |t|
t.string "email"
t.text "body"
t.integer "job_id"
t.datetime "created_at"
t.datetime "updated_at"
t.string "cv_file_name"
t.string "cv_content_type"
t.integer "cv_file_size"
t.datetime "cv_updated_at"
t.string "token"
end
create_table "assignments", :force => true do |t|
t.integer "user_id"
t.integer "role_id"
t.datetime "created_at"
t.datetime "updated_at"
end
- create_table "brain_busters", :force => true do |t|
- t.string "question"
- t.string "answer"
- end
-
create_table "categories", :force => true do |t|
t.string "name"
t.string "permalink"
t.integer "position", :default => 0
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "frameworks", :force => true do |t|
t.string "name"
t.string "permalink"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "jobs", :force => true do |t|
t.integer "type_id", :default => 0
t.integer "price_from"
t.integer "price_to"
t.boolean "remote_job"
t.string "title"
t.string "permalink"
t.text "description"
t.date "end_at"
t.string "company_name"
t.string "website"
t.integer "localization_id"
t.string "nip"
t.string "regon"
t.string "krs"
t.string "email"
t.datetime "created_at"
t.datetime "updated_at"
t.integer "framework_id"
t.float "rank"
t.string "token"
t.boolean "published"
t.integer "visits_count", :default => 0
t.boolean "apply_online", :default => true
t.integer "applicants_count", :default => 0
t.integer "category_id"
t.string "email_title"
t.integer "language_id"
end
create_table "languages", :force => true do |t|
t.string "name"
t.string "permalink"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "localizations", :force => true do |t|
t.string "name"
t.string "permalink"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "pages", :force => true do |t|
t.string "name"
t.string "permalink"
t.text "body"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "roles", :force => true do |t|
t.string "name"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "users", :force => true do |t|
t.string "login"
t.string "email", :null => false
t.string "crypted_password", :null => false
t.string "password_salt", :null => false
t.string "persistence_token", :null => false
t.integer "login_count", :default => 0, :null => false
t.datetime "last_request_at"
t.datetime "last_login_at"
t.datetime "current_login_at"
t.string "last_login_ip"
t.string "current_login_ip"
t.datetime "created_at"
t.datetime "updated_at"
- t.integer "visits_count", :default => 0
end
add_index "users", ["email"], :name => "index_users_on_email"
add_index "users", ["last_request_at"], :name => "index_users_on_last_request_at"
add_index "users", ["login"], :name => "index_users_on_login"
add_index "users", ["persistence_token"], :name => "index_users_on_persistence_token"
create_table "visits", :force => true do |t|
t.integer "job_id"
t.datetime "created_at"
t.datetime "updated_at"
t.integer "ip", :limit => 8
end
end
|
macbury/webpraca
|
adfa004c85584379e954b651af3c78eb1bf1422d
|
Nowa rekalkulacja
|
diff --git a/app/controllers/jobs_controller.rb b/app/controllers/jobs_controller.rb
index f5adf30..0e86402 100644
--- a/app/controllers/jobs_controller.rb
+++ b/app/controllers/jobs_controller.rb
@@ -1,222 +1,196 @@
class JobsController < ApplicationController
validates_captcha :only => [:create, :new]
ads_pos :bottom
ads_pos :right, :except => [:home, :index, :search]
ads_pos :none, :only => [:home]
-
- def widget
- @jobs = Job.active.all(:order => "rank DESC, created_at DESC", :limit => 15, :include => [:category, :localization])
- @options = {
- :width => "270px",
- :background => "#FFFFFF",
- :border => "#CCCCCC",
-
- }.merge!(params)
-
- @jobs_hash = @jobs.map do |job|
- {
- :title => job.title,
- :id => job.id,
- :type => JOB_LABELS[job.type_id],
- :category => job.category.name,
- :company => job.company_name,
- :localization => job.localization.name,
- :url => seo_job_url(job)
- }
- end
-
- respond_to do |format|
- format.js
- end
- end
-
+
def home
set_meta_tags :title => 'najpopularniejsze i najnowsze oferty pracy z IT',
:separator => " - "
query = Job.active.search
@recent_jobs = query.all(:order => "created_at DESC", :limit => 15, :include => [:localization, :category])
@top_jobs = query.all(:order => "rank DESC, created_at DESC", :limit => 15, :include => [:localization, :category])
end
# GET /jobs
# GET /jobs.xml
def index
@query = Job.active.search
options = {
:page => params[:page],
:per_page => 35,
:order => "created_at DESC, rank DESC",
:include => [:localization, :category]
}
if params[:order] =~ /najpopularniejsze/i
@page_title = ['najpopularniejsze oferty pracy IT']
@order = :rank
options[:order] = "rank DESC, created_at DESC"
else
@order = :created_at
@page_title = ['najnowsze oferty pracy IT']
options[:order] = "created_at DESC, rank DESC"
end
if params[:language]
@language = Language.find_by_permalink!(params[:language])
@page_title << @language.name.downcase
@query.language_id_is(@language.id)
end
if params[:category]
@category = Category.find_by_permalink!(params[:category])
@page_title << @category.name.downcase
@query.category_id_is(@category.id)
end
if params[:localization]
@localization = Localization.find_by_permalink!(params[:localization])
@page_title << @localization.name.downcase
@query.localization_id_is(@localization.id)
end
if params[:framework]
@framework = Framework.find_by_permalink!(params[:framework])
@page_title << @framework.name.downcase
options[:include] << :framework
@query.framework_id_is(@framework.id)
end
if params[:type_id]
@type_id = JOB_LABELS.index(params[:type_id]) || 0
@page_title << JOB_LABELS[@type_id].downcase
@query.type_id_is(@type_id)
end
@jobs = @query.paginate(options)
respond_to do |format|
format.html # index.html.erb
format.rss
format.atom
end
end
def search
@page_title = ["Szukaj oferty"]
@search = Job.active.search(params[:search])
if params[:search]
@page_title = ["Znalezione oferty"]
@jobs = @search.paginate( :page => params[:page],
:per_page => 30,
:order => "created_at DESC, rank DESC" )
end
respond_to do |format|
format.html
format.rss { render :action => "index" }
format.atom { render :action => "index" }
end
end
# GET /jobs/1
# GET /jobs/1.xml
def show
@job = Job.find_by_permalink!(params[:id])
@job.visited_by(request.remote_ip)
@category = @job.category
@page_title = ["oferta pracy IT", @job.category.name.downcase, @job.localization.name.downcase, @job.company_name.downcase, @job.title.downcase]
@tags = WebSiteConfig['website']['tags'].split(',').map(&:strip) + [@job.category.name, @job.localization.name, @job.company_name]
@tags << JOB_LABELS[@job.type_id]
unless @job.framework.nil?
@tags << @job.framework.name
@page_title.insert(1, @job.framework.name)
end
unless @job.language.nil?
@page_title.insert(1, @job.language.name)
@tags << @job.language.name
end
set_meta_tags :keywords => @tags.join(', ')
respond_to do |format|
format.html # show.html.erb
end
end
# GET /jobs/new
# GET /jobs/new.xml
def new
@job = Job.new
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @job }
end
end
# POST /jobs
# POST /jobs.xml
def create
@job = Job.new(params[:job])
respond_to do |format|
if @job.save
flash[:notice] = 'Na twój e-mail zostaÅ wysÅany link którym opublikujesz ofertÄ.'
format.html { redirect_to(@job) }
format.xml { render :xml => @job, :status => :created, :location => @job }
else
format.html { render :action => "new" }
format.xml { render :xml => @job.errors, :status => :unprocessable_entity }
end
end
end
# GET /jobs/1/edit
def edit
@job = Job.find_by_permalink_and_token!(params[:id], params[:token])
render :action => "new"
end
# PUT /jobs/1
# PUT /jobs/1.xml
def update
@job = Job.find_by_permalink_and_token!(params[:id], params[:token])
respond_to do |format|
if @job.update_attributes(params[:job])
flash[:notice] = 'Zapisano zmiany w ofercie.'
format.html { redirect_to(@job) }
format.xml { head :ok }
else
format.html { render :action => "new" }
format.xml { render :xml => @job.errors, :status => :unprocessable_entity }
end
end
end
def publish
@job = Job.find_by_permalink_and_token!(params[:id], params[:token])
unless @job.published
@job.publish!
flash[:notice] = "Twoja oferta jest już widoczna!"
end
redirect_to @job
end
# DELETE /jobs/1
# DELETE /jobs/1.xml
def destroy
@job = Job.find_by_permalink_and_token!(params[:id], params[:token])
@job.destroy
flash[:notice] = "Oferta zostaÅa usuniÄta"
respond_to do |format|
format.html { redirect_to(jobs_url) }
format.xml { head :ok }
end
end
end
diff --git a/app/controllers/widgets_controller.rb b/app/controllers/widgets_controller.rb
new file mode 100644
index 0000000..9534726
--- /dev/null
+++ b/app/controllers/widgets_controller.rb
@@ -0,0 +1,36 @@
+class WidgetsController < ApplicationController
+ before_filter :widget_from_params
+ ads_pos :right
+
+ def new
+
+ end
+
+ def show
+ @jobs = Job.active.all(:order => "RANDOM(), rank DESC, created_at DESC", :limit => 15, :include => [:localization])
+
+ @jobs_hash = @jobs.map do |job|
+ {
+ :title => "#{job.title} dla #{job.company_name} w #{job.localization.name}",
+ :id => job.id,
+ :type => JOB_LABELS[job.type_id],
+ :url => seo_job_url(job)
+ }
+ end
+
+ respond_to do |format|
+ format.js { render :layout => false }
+ end
+ end
+
+ protected
+
+ def widget_from_params
+ @options = {
+ :width => "270px",
+ :background => "#FFFFFF",
+ :border => "#CCCCCC",
+
+ }.merge!(params)
+ end
+end
diff --git a/app/helpers/widget_helper.rb b/app/helpers/widget_helper.rb
new file mode 100644
index 0000000..21f38fc
--- /dev/null
+++ b/app/helpers/widget_helper.rb
@@ -0,0 +1,2 @@
+module WidgetHelper
+end
diff --git a/app/models/job.rb b/app/models/job.rb
index 58f2c04..63888ee 100644
--- a/app/models/job.rb
+++ b/app/models/job.rb
@@ -1,179 +1,180 @@
JOB_TYPES = ["zlecenie (konkretna usÅuga do wykonania)", "poszukiwanie wspóÅpracowników / oferta pracy", "wolontariat (praca za reklamy, bannery, itp. lub praca za darmo)", "staż/praktyka"]
JOB_LABELS = ["zlecenie", "etat", "wolontariat", "praktyka"]
JOB_ETAT = 1;
JOB_RANK_VALUES = {
:default => 0.3,
:price => 0.8,
:krs => 0.6,
:nip => 0.5,
:regon => 0.6,
:framework_id => 0.7,
:language_id => 0.7,
:website => 0.4,
:apply_online => 0.3
}
class Job < ActiveRecord::Base
include ActionController::UrlWriter
xss_terminate
has_permalink :title
named_scope :active, :conditions => ["((jobs.end_at >= ?) AND (jobs.published = ?))", Date.current, true]
named_scope :old, :conditions => ["jobs.end_at < ?", Date.current]
named_scope :has_text, lambda { |text| { :conditions => ["((jobs.title ILIKE ?) OR (jobs.description ILIKE ?))", "%#{text}%", "%#{text}%"] } }
validates_presence_of :title, :description, :email, :company_name, :localization_id, :category_id
validates_length_of :title, :within => 3..255
validates_length_of :description, :within => 10..5000
validates_inclusion_of :type_id, :in => 0..JOB_TYPES.size-1
validates_inclusion_of :availability_time, :in => 1..60
validates_numericality_of :price_from,
:greater_than => 0,
:unless => Proc.new { |j| j.price_from.nil? }
validates_numericality_of :price_to,
:greater_than => 0,
:unless => Proc.new { |j| j.price_to.nil? }
validates_format_of :email, :with => /([a-z0-9_.-]+)@([a-z0-9-]+)\.([a-z.]+)/i
validates_format_of :website, :with => /(^$)|(^(http|https):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(([0-9]{1,5})?\/.*)?$)/ix
validates_format_of :regon,
:with => /(^$)|(^[0-9]{7,14}$)/
validates_format_of :nip,
:with => /(^$)|(^\d{2,3}-\d{2,3}-\d{2,3}-\d{2,3}$)/
validates_format_of :krs,
:with => /(^$)|(^\d{10})$/
belongs_to :framework
belongs_to :localization
belongs_to :category
belongs_to :language
has_many :applicants, :dependent => :delete_all
has_many :visits, :dependent => :delete_all
attr_protected :rank, :permalink, :end_at, :token, :published
attr_accessor :framework_name, :localization_name
before_create :create_from_name, :generate_token
before_save :calculate_rank
after_create :send_notification
def self.find_grouped_by_type
return Job.active.count(:type_id, :group => "type_id")
end
def send_notification
JobMailer.deliver_job_posted(self)
end
def generate_token
alphanumerics = ('a'..'z').to_a.concat(('A'..'Z').to_a.concat(('0'..'9').to_a))
salt = alphanumerics.sort_by{rand}.to_s[0..1024]
self.token = Digest::SHA1.hexdigest("--#{salt}--#{self.id}--#{Date.current}--")
generate_token unless Job.find_by_token(self.token).nil?
end
def calculate_rank
self.rank = 1.0
- self.rank += visits_count * 0.01 unless visits_count.nil?
+ self.rank += visits_count * 0.001 unless visits_count.nil?
+ self.rank += applicants_count * 0.01 unless applicants_count.nil?
- [:regon, :nip, :krs, :framework_id, :website, :apply_online].each do |attribute|
+ [:regon, :nip, :krs, :framework_id, :website, :apply_online, :language_id].each do |attribute|
val = send(attribute)
inc = JOB_RANK_VALUES[attribute] || JOB_RANK_VALUES[:default]
self.rank += inc unless (val.nil? || (val.class == String && val.empty?) || (val.class == TrueClass))
end
if pay_band?
self.rank += JOB_RANK_VALUES[:price]
price = price_from || price_to
if price >= 10_000 # ciekawe czy ktoÅ da tyle :P
self.rank += 0.8
elsif price >= 7000
self.rank += 0.7
elsif price >= 5000
self.rank += 0.6
elsif price >= 3000
self.rank += 0.3
elsif price < 2000
if self.type_id == JOB_ETAT
self.rank -= 0.6 # bo nikt za grosze nie chce pracowaÄ
else
self.rank += 0.3 # chyba że to biedny student
end
end
end
end
def pay_band?
((!self.price_from.nil? && self.price_from > 0) || (!self.price_to.nil? && self.price_to > 0))
end
def create_from_name
unless (self.framework_name.nil? || self.framework_name.blank?)
framework = Framework.name_like(self.framework_name).first
framework = Framework.create(:name => self.framework_name) if framework.nil?
self.framework = framework
end
unless (self.localization_name.nil? || self.localization_name.blank?)
localization = Localization.name_like(self.localization_name).first
localization = Localization.create(:name => self.localization_name) if localization.nil?
self.localization = localization
end
end
def availability_time
date = created_at.nil? ? Date.current.to_date : created_at.to_date
return (read_attribute(:end_at) - date).to_i rescue 14
end
def availability_time=(val)
date = created_at.nil? ? Date.current.to_date : created_at.to_date
write_attribute(:end_at, date+val.to_i.days)
end
def highlighted?
self.rank >= 4.75
end
def publish!
self.published = true
save
spawn do
tags = [localization.name, category.name, "praca", JOB_LABELS[self.type_id]]
tags << framework.name unless framework.nil?
tags << language.name unless language.nil?
MicroFeed.send :streams => :all,
:msg => "[#{company_name}] - #{title}",
:tags => tags,
:link => seo_job_url(self, :host => "webpraca.net") if Rails.env == "production"
end
end
def visited_by(ip)
visit = visits.find_or_create_by_ip(IPAddr.new(ip).to_i)
visits_count += 1 if visit.new_record?
save
end
def to_param
permalink
end
end
diff --git a/app/views/layouts/application.html.erb b/app/views/layouts/application.html.erb
index 2fc7029..ed659e2 100644
--- a/app/views/layouts/application.html.erb
+++ b/app/views/layouts/application.html.erb
@@ -1,91 +1,92 @@
<!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" lang="pl">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="google-site-verification" content="zE20xzrx6CCNbFsmsNTok9xaPavS0Cmu7hJxdUbNqN8" />
<%= display_meta_tags :site => WebSiteConfig['website']['name'] %>
<meta name="viewport" content="width=900" />
<%= rss_link("RSS", jobs_url(:format => :rss)) %>
<%= rss_link("ATOM", jobs_url(:format => :atom)) %>
<%= javascript_tag "window._token = '#{form_authenticity_token}'" %>
<%= javascript_include_merged :base %>
<%= stylesheet_link_merged :base %>
</head>
<body>
<div class="wrapper">
<div class="header">
<h1 id="logo"><%= link_to WebSiteConfig['website']['name'], root_path %></h1>
<ul class="categories">
<li class="right">
<%= link_to "Najpopularniejsze", seo_jobs_path(:order => 'najpopularniejsze', :category => params[:category]), :class => (!@order.nil? && @order == :rank) ? "selected" : "normal" %>
</li>
<li class="right">
<%= link_to "Najnowsze", seo_jobs_path(:order => 'najnowsze', :category => params[:category] ), :class => (!@order.nil? && @order == :created_at) ? "selected" : "normal" %>
</li>
<% for category in Category.all(:order => "position") %>
<li>
<%= link_to category.name, seo_jobs_path(:order => params[:order], :category => category.permalink), :class => (!@category.nil? && @category.id == category.id) ? "selected" : "normal" %>
</li>
<% end %>
</ul>
<ul class="menu">
<li><%= link_to "Strona gÅówna", root_path %></li>
<li><%= link_to "Szukaj", search_jobs_path %></li>
<li><%= link_to "Informacje", "/strona/informacje/" %></li>
<li><%= link_to "Regulamin", "/strona/regulamin/" %></li>
<li><%= link_to "Obserwuj nas", "/strona/obserwuj-nas" %></li>
<li><%= link_to "Kontakt", contact_path %></li>
+ <li><%= link_to "Gadżet na stronÄ", new_widget_path %></li>
</ul>
</div>
<%- flash.each do |name, msg| -%>
<div class="<%= "flash #{name}" %>">
<a href="#" class="dismiss">X</a>
<p><%= msg %></p>
</div>
<%- end -%>
<div class="sidebar">
<div class="box">
<%= link_to "Dodaj ofertÄ za DARMO!", new_job_path, :id => "add_job", :class => "more", :rel => "nofollow" %>
</div>
<%= yield :sidebar %>
<% if @ads_pos == :right %>
<div class="box">
<div>
<%= render :partial => "/shared/ads" %>
</div>
</div>
<% end %>
</div>
<div class="content">
<%= yield %>
<% if @ads_pos == :bottom %>
<div class="box">
<div>
<%= render :partial => "/shared/ads" %>
</div>
</div>
<% end %>
</div>
<div class="clear"></div>
</div>
<%= render :partial => "/shared/footer" %>
<script type="text/javascript" src="http://flaker.pl/track/site/1122612"></script>
<script type="text/javascript" src="http://app.sugester.pl/webpraca/widget.js"></script>
<script type="text/javascript">
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script>
<script type="text/javascript">
try {
var pageTracker = _gat._getTracker("UA-11469054-5");
pageTracker._trackPageview();
} catch(err) {}</script>
</body>
</html>
\ No newline at end of file
diff --git a/app/views/widgets/new.html.erb b/app/views/widgets/new.html.erb
new file mode 100644
index 0000000..34c6b0f
--- /dev/null
+++ b/app/views/widgets/new.html.erb
@@ -0,0 +1,21 @@
+<% title "Gadżet z ofertami na stronÄ WWW" %>
+<div class="box">
+ <div>
+ <div class="title">
+ <h2>Konfiguruj</h2>
+ </div>
+
+
+ </div>
+</div>
+
+<div class="box">
+ <div>
+ <div class="title mini">
+ <h3>PodglÄ
d</h3>
+ </div>
+
+
+ <script type="text/javascript" charset="utf-8" src="http://0.0.0.0:3000/widget"></script>
+ </div>
+</div>
\ No newline at end of file
diff --git a/app/views/widgets/show.js.erb b/app/views/widgets/show.js.erb
new file mode 100644
index 0000000..52d2473
--- /dev/null
+++ b/app/views/widgets/show.js.erb
@@ -0,0 +1,20 @@
+(function(){
+ var jobs = <%= @jobs_hash.to_json %>;
+
+ document.write('<div class="webpraca_job_board" style="<%= " border:1px solid #{@options[:border]} !important; background-color: #{@options[:background]} !important; width: #{@options[:width]} !important; padding:0px !important; text-decoration:none !important; ".gsub('\n', '').gsub('\t', '') -%>">');
+
+ document.write('<ul style="margin: 0px !important; margin-top: 0px !important; padding: 5px !important; text-indent:0px !important;">');
+
+ for (var i=0; i < jobs.length; i++) {
+ var job = jobs[i];
+ document.write('<li style="margin:0px !important; padding:0px !important; text-indent:0px !important; font-family:Arial,Helvetica !important; list-style-type:none !important; line-height:15px !important;">');
+
+ document.write('<a href="'+job.url+'" style="margin:0px !important; padding:0px !important; text-indent:0px !important; font: 12px Arial,Helvetica !important; line-height:15px !important; text-decoration: none;">'+job.title+'</a>');
+
+ document.write('</li>');
+ };
+
+ document.write('<li style="margin-left:0px!important;margin-right:0px!important;margin-bottom:0px!important;margin-top:0px!important;text-align:right;!important; padding-top:3px!important;padding-bottom:2px!important;padding-left:0px!important;padding-right:0px!important;line-height:9px!important;list-style-type:none!important;font-family:Arial,Helvetica!important;">');
+ document.write('<span style="font-family:Arial,Helvetica!important;font-weight:normal!important;font-size:10px!important;color:#777777!important;text-decoration:none!important;"><a style="font-family:Arial,Helvetica!important;text-decoration:none!important;border:none!important;color:inherit;" href="<%= root_url %>">webpraca.net oferty pracy, zlecenia it</a></span></li>');
+ document.write('</ul></div>');
+})();
\ No newline at end of file
diff --git a/config/routes.rb b/config/routes.rb
index 50d551d..344e157 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -1,89 +1,90 @@
ActionController::Routing::Routes.draw do |map|
map.new_contact '/contact/new', :controller => 'contact', :action => 'new', :conditions => { :method => :get }
map.contact '/contact', :controller => 'contact', :action => 'new', :conditions => { :method => :get }
map.contact '/contact', :controller => 'contact', :action => 'create', :conditions => { :method => :post }
map.seo_page '/strona/:id/', :controller => 'admin/pages', :action => 'show'
map.with_options :controller => 'jobs', :action => 'index' do |job|
job.with_options :category => nil, :page => 1, :order => "najnowsze", :requirements => { :order => /(najnowsze|najpopularniejsze)/, :page => /\d/ } do |seo|
seo.connect '/oferty/:page'
seo.connect '/oferty/:order'
seo.connect '/oferty/:order/:page'
seo.seo_jobs '/oferty/:order/:category/:page'
end
job.connect '/lokalizacja/:localization/:page'
job.localization '/lokalizacja/:localization'
job.connect '/framework/:framework/:page'
job.framework '/framework/:framework'
job.connect '/jezyk/:language/:page'
job.language '/jezyk/:language'
job.connect '/typ/:type_id/:page'
job.job_type '/typ/:type_id'
job.connect '/kategoria/:category/:page'
job.job_category '/kategoria/:category'
end
map.resources :jobs, :member => { :publish => :get, :destroy => :any }, :collection => { :search => :any, :widget => :get } do |jobs|
jobs.resources :applicants, :member => { :download => :get }
end
- map.resources :user_sessions
+ map.resource :widget
+ map.resources :user_sessions
map.login '/login', :controller => 'user_sessions', :action => 'new'
map.logout '/logout', :controller => 'user_sessions', :action => 'destroy'
map.namespace :admin do |admin|
admin.stats '/stats', :controller => "stats"
admin.config '/config', :controller => "configs", :action => "new"
admin.resources :pages
admin.resources :jobs
admin.resource :configs
admin.resources :frameworks
admin.resources :categories, :collection => { :reorder => :post }
end
map.admin '/admin', :controller => "admin/stats"
# The priority is based upon order of creation: first created -> highest priority.
# Sample of regular route:
# map.connect 'products/:id', :controller => 'catalog', :action => 'view'
# Keep in mind you can assign values other than :controller and :action
# Sample of named route:
# map.purchase 'products/:id/purchase', :controller => 'catalog', :action => 'purchase'
# This route can be invoked with purchase_url(:id => product.id)
# Sample resource route (maps HTTP verbs to controller actions automatically):
# map.resources :products
# Sample resource route with options:
# map.resources :products, :member => { :short => :get, :toggle => :post }, :collection => { :sold => :get }
# Sample resource route with sub-resources:
# map.resources :products, :has_many => [ :comments, :sales ], :has_one => :seller
# Sample resource route with more complex sub-resources
# map.resources :products do |products|
# products.resources :comments
# products.resources :sales, :collection => { :recent => :get }
# end
# Sample resource route within a namespace:
# map.namespace :admin do |admin|
# # Directs /admin/products/* to Admin::ProductsController (app/controllers/admin/products_controller.rb)
# admin.resources :products
# end
map.root :controller => "jobs", :action => "home"
map.seo_job '/:id', :controller => 'jobs', :action => 'show'
# You can have the root of your site routed with map.root -- just remember to delete public/index.html.
# See how all your routes lay out with "rake routes"
# Install the default routes as the lowest priority.
# Note: These default routes make all actions in every controller accessible via GET requests. You should
# consider removing or commenting them out if you're using named routes and resources.
map.connect ':controller/:action/:id'
map.connect ':controller/:action/:id.:format'
end
|
macbury/webpraca
|
30e2d8989f96018da8ab094851c3a7b27682d494
|
Seo: nofollow links
|
diff --git a/app/views/jobs/show.html.erb b/app/views/jobs/show.html.erb
index 5041a41..a8eff1d 100644
--- a/app/views/jobs/show.html.erb
+++ b/app/views/jobs/show.html.erb
@@ -1,88 +1,88 @@
<div class="box">
<div>
<div class="title">
<h2>
<%= @job.title %>
</h2>
</div>
<dl>
<dt>Typ</dt>
<dd><%= job_label(@job) %></dd>
<dt>Kategoria</dt>
<dd><%= link_to @job.category.name, job_category_path(@job.category) %></dd>
<dt>Ocena</dt>
<dd><%= format_rank(@job.rank) %></dd>
<dt>Pracodawca</dt>
<dd><%= link_to @job.company_name, @job.website, :target => "_blank" %></dd>
<dt>Lokalizacja</dt>
<dd><%= link_to @job.localization.name, localization_path(@job.localization) %></dd>
<% unless @job.framework.nil? %>
<dt>Framework</dt>
<dd><%= link_to @job.framework.name, framework_path(@job.framework) %></dd>
<% end %>
<% unless @job.language.nil? %>
<dt>JÄzyk</dt>
<dd><%= link_to @job.language.name, language_path(@job.language) %></dd>
<% end %>
<% if @job.pay_band? %>
<dt>WideÅko zarobkowe</dt>
<dd>
<%= "od #{number_to_currency(@job.price_from)}" unless @job.price_from.nil? %>
<%= "do #{number_to_currency(@job.price_to)}" unless @job.price_to.nil? %> na miesiÄ
c, netto
</dd>
<% end %>
<% unless @job.apply_online %>
<dt>Kontakt</dt>
<dd><%= link_to "Formularz kontaktowy", contact_path(:job_id => @job.id) %></dd>
<% end %>
<% unless (@job.regon.nil? || @job.regon.empty?) %>
<dt>REGON</dt>
<dd><%= @job.regon %> </dd>
<% end %>
<% unless (@job.nip.nil? || @job.nip.empty?) %>
<dt>NIP</dt>
<dd><%= @job.nip %> </dd>
<% end %>
<% unless (@job.krs.nil? || @job.krs.empty?) %>
<dt>KRS</dt>
<dd><%= link_to @job.krs, "http://krs.ms.gov.pl/Podmiot.aspx?nrkrs=#{@job.krs}", :target => "_blank" %> </dd>
<% end %>
<dt>Data rozpoczÄcia</dt>
<dd>
<%= l @job.created_at, :format => :long %>
<br />
<abbr title="<%= @job.created_at.xmlschema %>"><%= distance_of_time_in_words_to_now @job.created_at %> temu</abbr>
</dd>
<dt>Data zakoÅczenia</dt>
<dd>
<%= l @job.end_at, :format => :long %>
<br />
za <abbr title="<%= @job.end_at.xmlschema %>"><%= distance_of_time_in_words_to_now(@job.end_at) %></abbr>
</dd>
<dt>WyÅwietlona</dt>
<dd><%= @job.visits_count %> razy</dd>
</dl>
<div class="clear"></div>
</div>
<div>
<div class="title mini">
<h3>Opis oferty</h3>
</div>
<div class="text">
<%= RedCloth.new(highlight(@job.description, @tags, :highlighter => '<i>\1</i>')).to_html %>
</div>
<p>
<% if permitted_to? :edit, @job %>
<%= link_to 'Edytuj', edit_job_path(@job) %> |
<%= link_to 'Wstecz', jobs_path %>
<% end %>
</p>
</div>
- <%= link_to 'Aplikuj online!', new_job_applicant_path(@job), :class => "more" if @job.apply_online %>
+ <%= link_to 'Aplikuj online!', new_job_applicant_path(@job), :class => "more", :rel => "nofollow" if @job.apply_online %>
</div>
diff --git a/app/views/layouts/application.html.erb b/app/views/layouts/application.html.erb
index 7267aca..2fc7029 100644
--- a/app/views/layouts/application.html.erb
+++ b/app/views/layouts/application.html.erb
@@ -1,91 +1,91 @@
<!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" lang="pl">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="google-site-verification" content="zE20xzrx6CCNbFsmsNTok9xaPavS0Cmu7hJxdUbNqN8" />
<%= display_meta_tags :site => WebSiteConfig['website']['name'] %>
<meta name="viewport" content="width=900" />
<%= rss_link("RSS", jobs_url(:format => :rss)) %>
<%= rss_link("ATOM", jobs_url(:format => :atom)) %>
<%= javascript_tag "window._token = '#{form_authenticity_token}'" %>
<%= javascript_include_merged :base %>
<%= stylesheet_link_merged :base %>
</head>
<body>
<div class="wrapper">
<div class="header">
<h1 id="logo"><%= link_to WebSiteConfig['website']['name'], root_path %></h1>
<ul class="categories">
<li class="right">
<%= link_to "Najpopularniejsze", seo_jobs_path(:order => 'najpopularniejsze', :category => params[:category]), :class => (!@order.nil? && @order == :rank) ? "selected" : "normal" %>
</li>
<li class="right">
<%= link_to "Najnowsze", seo_jobs_path(:order => 'najnowsze', :category => params[:category] ), :class => (!@order.nil? && @order == :created_at) ? "selected" : "normal" %>
</li>
<% for category in Category.all(:order => "position") %>
<li>
<%= link_to category.name, seo_jobs_path(:order => params[:order], :category => category.permalink), :class => (!@category.nil? && @category.id == category.id) ? "selected" : "normal" %>
</li>
<% end %>
</ul>
<ul class="menu">
<li><%= link_to "Strona gÅówna", root_path %></li>
<li><%= link_to "Szukaj", search_jobs_path %></li>
<li><%= link_to "Informacje", "/strona/informacje/" %></li>
<li><%= link_to "Regulamin", "/strona/regulamin/" %></li>
<li><%= link_to "Obserwuj nas", "/strona/obserwuj-nas" %></li>
<li><%= link_to "Kontakt", contact_path %></li>
</ul>
</div>
<%- flash.each do |name, msg| -%>
<div class="<%= "flash #{name}" %>">
<a href="#" class="dismiss">X</a>
<p><%= msg %></p>
</div>
<%- end -%>
<div class="sidebar">
<div class="box">
- <%= link_to "Dodaj ofertÄ za DARMO!", new_job_path, :id => "add_job", :class => "more" %>
+ <%= link_to "Dodaj ofertÄ za DARMO!", new_job_path, :id => "add_job", :class => "more", :rel => "nofollow" %>
</div>
<%= yield :sidebar %>
<% if @ads_pos == :right %>
<div class="box">
<div>
<%= render :partial => "/shared/ads" %>
</div>
</div>
<% end %>
</div>
<div class="content">
<%= yield %>
<% if @ads_pos == :bottom %>
<div class="box">
<div>
<%= render :partial => "/shared/ads" %>
</div>
</div>
<% end %>
</div>
<div class="clear"></div>
</div>
<%= render :partial => "/shared/footer" %>
<script type="text/javascript" src="http://flaker.pl/track/site/1122612"></script>
<script type="text/javascript" src="http://app.sugester.pl/webpraca/widget.js"></script>
<script type="text/javascript">
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script>
<script type="text/javascript">
try {
var pageTracker = _gat._getTracker("UA-11469054-5");
pageTracker._trackPageview();
} catch(err) {}</script>
</body>
</html>
\ No newline at end of file
|
macbury/webpraca
|
03f9f7ab8c679dfbd3a20f610b513e0d902827bd
|
Spawn it
|
diff --git a/app/models/job.rb b/app/models/job.rb
index 5bb49ac..58f2c04 100644
--- a/app/models/job.rb
+++ b/app/models/job.rb
@@ -1,178 +1,179 @@
JOB_TYPES = ["zlecenie (konkretna usÅuga do wykonania)", "poszukiwanie wspóÅpracowników / oferta pracy", "wolontariat (praca za reklamy, bannery, itp. lub praca za darmo)", "staż/praktyka"]
JOB_LABELS = ["zlecenie", "etat", "wolontariat", "praktyka"]
JOB_ETAT = 1;
JOB_RANK_VALUES = {
:default => 0.3,
:price => 0.8,
:krs => 0.6,
:nip => 0.5,
:regon => 0.6,
:framework_id => 0.7,
:language_id => 0.7,
:website => 0.4,
:apply_online => 0.3
}
class Job < ActiveRecord::Base
include ActionController::UrlWriter
xss_terminate
has_permalink :title
named_scope :active, :conditions => ["((jobs.end_at >= ?) AND (jobs.published = ?))", Date.current, true]
named_scope :old, :conditions => ["jobs.end_at < ?", Date.current]
named_scope :has_text, lambda { |text| { :conditions => ["((jobs.title ILIKE ?) OR (jobs.description ILIKE ?))", "%#{text}%", "%#{text}%"] } }
validates_presence_of :title, :description, :email, :company_name, :localization_id, :category_id
validates_length_of :title, :within => 3..255
validates_length_of :description, :within => 10..5000
validates_inclusion_of :type_id, :in => 0..JOB_TYPES.size-1
validates_inclusion_of :availability_time, :in => 1..60
validates_numericality_of :price_from,
:greater_than => 0,
:unless => Proc.new { |j| j.price_from.nil? }
validates_numericality_of :price_to,
:greater_than => 0,
:unless => Proc.new { |j| j.price_to.nil? }
validates_format_of :email, :with => /([a-z0-9_.-]+)@([a-z0-9-]+)\.([a-z.]+)/i
validates_format_of :website, :with => /(^$)|(^(http|https):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(([0-9]{1,5})?\/.*)?$)/ix
validates_format_of :regon,
:with => /(^$)|(^[0-9]{7,14}$)/
validates_format_of :nip,
:with => /(^$)|(^\d{2,3}-\d{2,3}-\d{2,3}-\d{2,3}$)/
validates_format_of :krs,
:with => /(^$)|(^\d{10})$/
belongs_to :framework
belongs_to :localization
belongs_to :category
belongs_to :language
has_many :applicants, :dependent => :delete_all
has_many :visits, :dependent => :delete_all
attr_protected :rank, :permalink, :end_at, :token, :published
attr_accessor :framework_name, :localization_name
before_create :create_from_name, :generate_token
before_save :calculate_rank
after_create :send_notification
def self.find_grouped_by_type
return Job.active.count(:type_id, :group => "type_id")
end
def send_notification
JobMailer.deliver_job_posted(self)
end
def generate_token
alphanumerics = ('a'..'z').to_a.concat(('A'..'Z').to_a.concat(('0'..'9').to_a))
salt = alphanumerics.sort_by{rand}.to_s[0..1024]
self.token = Digest::SHA1.hexdigest("--#{salt}--#{self.id}--#{Date.current}--")
generate_token unless Job.find_by_token(self.token).nil?
end
def calculate_rank
self.rank = 1.0
self.rank += visits_count * 0.01 unless visits_count.nil?
[:regon, :nip, :krs, :framework_id, :website, :apply_online].each do |attribute|
val = send(attribute)
inc = JOB_RANK_VALUES[attribute] || JOB_RANK_VALUES[:default]
self.rank += inc unless (val.nil? || (val.class == String && val.empty?) || (val.class == TrueClass))
end
if pay_band?
self.rank += JOB_RANK_VALUES[:price]
price = price_from || price_to
if price >= 10_000 # ciekawe czy ktoÅ da tyle :P
self.rank += 0.8
elsif price >= 7000
self.rank += 0.7
elsif price >= 5000
self.rank += 0.6
elsif price >= 3000
self.rank += 0.3
elsif price < 2000
if self.type_id == JOB_ETAT
self.rank -= 0.6 # bo nikt za grosze nie chce pracowaÄ
else
self.rank += 0.3 # chyba że to biedny student
end
end
end
end
def pay_band?
((!self.price_from.nil? && self.price_from > 0) || (!self.price_to.nil? && self.price_to > 0))
end
def create_from_name
unless (self.framework_name.nil? || self.framework_name.blank?)
framework = Framework.name_like(self.framework_name).first
framework = Framework.create(:name => self.framework_name) if framework.nil?
self.framework = framework
end
unless (self.localization_name.nil? || self.localization_name.blank?)
localization = Localization.name_like(self.localization_name).first
localization = Localization.create(:name => self.localization_name) if localization.nil?
self.localization = localization
end
end
def availability_time
date = created_at.nil? ? Date.current.to_date : created_at.to_date
return (read_attribute(:end_at) - date).to_i rescue 14
end
def availability_time=(val)
date = created_at.nil? ? Date.current.to_date : created_at.to_date
write_attribute(:end_at, date+val.to_i.days)
end
def highlighted?
self.rank >= 4.75
end
def publish!
self.published = true
save
-
- tags = [localization.name, category.name, "praca", JOB_LABELS[self.type_id]]
- tags << framework.name unless framework.nil?
- tags << language.name unless language.nil?
- MicroFeed.send :streams => :all,
- :msg => "[#{company_name}] - #{title}",
- :tags => tags,
- :link => seo_job_url(self, :host => "webpraca.net") if Rails.env == "production"
-
+ spawn do
+ tags = [localization.name, category.name, "praca", JOB_LABELS[self.type_id]]
+ tags << framework.name unless framework.nil?
+ tags << language.name unless language.nil?
+
+ MicroFeed.send :streams => :all,
+ :msg => "[#{company_name}] - #{title}",
+ :tags => tags,
+ :link => seo_job_url(self, :host => "webpraca.net") if Rails.env == "production"
+ end
end
def visited_by(ip)
visit = visits.find_or_create_by_ip(IPAddr.new(ip).to_i)
visits_count += 1 if visit.new_record?
save
end
def to_param
permalink
end
end
|
macbury/webpraca
|
ea26902405ef408ab2b427961fbafe4e563c1875
|
Dodanie tagu z jezykiem do microfeeda
|
diff --git a/app/models/job.rb b/app/models/job.rb
index 8c9d09e..5bb49ac 100644
--- a/app/models/job.rb
+++ b/app/models/job.rb
@@ -1,177 +1,178 @@
JOB_TYPES = ["zlecenie (konkretna usÅuga do wykonania)", "poszukiwanie wspóÅpracowników / oferta pracy", "wolontariat (praca za reklamy, bannery, itp. lub praca za darmo)", "staż/praktyka"]
JOB_LABELS = ["zlecenie", "etat", "wolontariat", "praktyka"]
JOB_ETAT = 1;
JOB_RANK_VALUES = {
:default => 0.3,
:price => 0.8,
:krs => 0.6,
:nip => 0.5,
:regon => 0.6,
:framework_id => 0.7,
:language_id => 0.7,
:website => 0.4,
:apply_online => 0.3
}
class Job < ActiveRecord::Base
include ActionController::UrlWriter
xss_terminate
has_permalink :title
named_scope :active, :conditions => ["((jobs.end_at >= ?) AND (jobs.published = ?))", Date.current, true]
named_scope :old, :conditions => ["jobs.end_at < ?", Date.current]
named_scope :has_text, lambda { |text| { :conditions => ["((jobs.title ILIKE ?) OR (jobs.description ILIKE ?))", "%#{text}%", "%#{text}%"] } }
validates_presence_of :title, :description, :email, :company_name, :localization_id, :category_id
validates_length_of :title, :within => 3..255
validates_length_of :description, :within => 10..5000
validates_inclusion_of :type_id, :in => 0..JOB_TYPES.size-1
validates_inclusion_of :availability_time, :in => 1..60
validates_numericality_of :price_from,
:greater_than => 0,
:unless => Proc.new { |j| j.price_from.nil? }
validates_numericality_of :price_to,
:greater_than => 0,
:unless => Proc.new { |j| j.price_to.nil? }
validates_format_of :email, :with => /([a-z0-9_.-]+)@([a-z0-9-]+)\.([a-z.]+)/i
validates_format_of :website, :with => /(^$)|(^(http|https):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(([0-9]{1,5})?\/.*)?$)/ix
validates_format_of :regon,
:with => /(^$)|(^[0-9]{7,14}$)/
validates_format_of :nip,
:with => /(^$)|(^\d{2,3}-\d{2,3}-\d{2,3}-\d{2,3}$)/
validates_format_of :krs,
:with => /(^$)|(^\d{10})$/
belongs_to :framework
belongs_to :localization
belongs_to :category
belongs_to :language
has_many :applicants, :dependent => :delete_all
has_many :visits, :dependent => :delete_all
attr_protected :rank, :permalink, :end_at, :token, :published
attr_accessor :framework_name, :localization_name
before_create :create_from_name, :generate_token
before_save :calculate_rank
after_create :send_notification
def self.find_grouped_by_type
return Job.active.count(:type_id, :group => "type_id")
end
def send_notification
JobMailer.deliver_job_posted(self)
end
def generate_token
alphanumerics = ('a'..'z').to_a.concat(('A'..'Z').to_a.concat(('0'..'9').to_a))
salt = alphanumerics.sort_by{rand}.to_s[0..1024]
self.token = Digest::SHA1.hexdigest("--#{salt}--#{self.id}--#{Date.current}--")
generate_token unless Job.find_by_token(self.token).nil?
end
def calculate_rank
self.rank = 1.0
self.rank += visits_count * 0.01 unless visits_count.nil?
[:regon, :nip, :krs, :framework_id, :website, :apply_online].each do |attribute|
val = send(attribute)
inc = JOB_RANK_VALUES[attribute] || JOB_RANK_VALUES[:default]
self.rank += inc unless (val.nil? || (val.class == String && val.empty?) || (val.class == TrueClass))
end
if pay_band?
self.rank += JOB_RANK_VALUES[:price]
price = price_from || price_to
if price >= 10_000 # ciekawe czy ktoÅ da tyle :P
self.rank += 0.8
elsif price >= 7000
self.rank += 0.7
elsif price >= 5000
self.rank += 0.6
elsif price >= 3000
self.rank += 0.3
elsif price < 2000
if self.type_id == JOB_ETAT
self.rank -= 0.6 # bo nikt za grosze nie chce pracowaÄ
else
self.rank += 0.3 # chyba że to biedny student
end
end
end
end
def pay_band?
((!self.price_from.nil? && self.price_from > 0) || (!self.price_to.nil? && self.price_to > 0))
end
def create_from_name
unless (self.framework_name.nil? || self.framework_name.blank?)
framework = Framework.name_like(self.framework_name).first
framework = Framework.create(:name => self.framework_name) if framework.nil?
self.framework = framework
end
unless (self.localization_name.nil? || self.localization_name.blank?)
localization = Localization.name_like(self.localization_name).first
localization = Localization.create(:name => self.localization_name) if localization.nil?
self.localization = localization
end
end
def availability_time
date = created_at.nil? ? Date.current.to_date : created_at.to_date
return (read_attribute(:end_at) - date).to_i rescue 14
end
def availability_time=(val)
date = created_at.nil? ? Date.current.to_date : created_at.to_date
write_attribute(:end_at, date+val.to_i.days)
end
def highlighted?
self.rank >= 4.75
end
def publish!
self.published = true
save
tags = [localization.name, category.name, "praca", JOB_LABELS[self.type_id]]
tags << framework.name unless framework.nil?
+ tags << language.name unless language.nil?
MicroFeed.send :streams => :all,
:msg => "[#{company_name}] - #{title}",
:tags => tags,
:link => seo_job_url(self, :host => "webpraca.net") if Rails.env == "production"
end
def visited_by(ip)
visit = visits.find_or_create_by_ip(IPAddr.new(ip).to_i)
visits_count += 1 if visit.new_record?
save
end
def to_param
permalink
end
end
|
macbury/webpraca
|
aeb8dc7e756a5ab92f48de9d6dcbfd042e314e83
|
Zwiekszenie ilosci ofert na stronie domowej
|
diff --git a/app/controllers/jobs_controller.rb b/app/controllers/jobs_controller.rb
index 6d67a4b..f5adf30 100644
--- a/app/controllers/jobs_controller.rb
+++ b/app/controllers/jobs_controller.rb
@@ -1,222 +1,222 @@
class JobsController < ApplicationController
validates_captcha :only => [:create, :new]
ads_pos :bottom
ads_pos :right, :except => [:home, :index, :search]
ads_pos :none, :only => [:home]
def widget
- @jobs = Job.active.all(:order => "rank DESC, created_at DESC", :limit => 10, :include => [:category, :localization])
+ @jobs = Job.active.all(:order => "rank DESC, created_at DESC", :limit => 15, :include => [:category, :localization])
@options = {
:width => "270px",
:background => "#FFFFFF",
:border => "#CCCCCC",
}.merge!(params)
@jobs_hash = @jobs.map do |job|
{
:title => job.title,
:id => job.id,
:type => JOB_LABELS[job.type_id],
:category => job.category.name,
:company => job.company_name,
:localization => job.localization.name,
:url => seo_job_url(job)
}
end
respond_to do |format|
format.js
end
end
def home
set_meta_tags :title => 'najpopularniejsze i najnowsze oferty pracy z IT',
:separator => " - "
query = Job.active.search
- @recent_jobs = query.all(:order => "created_at DESC", :limit => 10, :include => [:localization, :category])
- @top_jobs = query.all(:order => "rank DESC, created_at DESC", :limit => 10, :include => [:localization, :category])
+ @recent_jobs = query.all(:order => "created_at DESC", :limit => 15, :include => [:localization, :category])
+ @top_jobs = query.all(:order => "rank DESC, created_at DESC", :limit => 15, :include => [:localization, :category])
end
# GET /jobs
# GET /jobs.xml
def index
@query = Job.active.search
options = {
:page => params[:page],
- :per_page => 25,
+ :per_page => 35,
:order => "created_at DESC, rank DESC",
:include => [:localization, :category]
}
if params[:order] =~ /najpopularniejsze/i
@page_title = ['najpopularniejsze oferty pracy IT']
@order = :rank
options[:order] = "rank DESC, created_at DESC"
else
@order = :created_at
@page_title = ['najnowsze oferty pracy IT']
options[:order] = "created_at DESC, rank DESC"
end
if params[:language]
@language = Language.find_by_permalink!(params[:language])
@page_title << @language.name.downcase
@query.language_id_is(@language.id)
end
if params[:category]
@category = Category.find_by_permalink!(params[:category])
@page_title << @category.name.downcase
@query.category_id_is(@category.id)
end
if params[:localization]
@localization = Localization.find_by_permalink!(params[:localization])
@page_title << @localization.name.downcase
@query.localization_id_is(@localization.id)
end
if params[:framework]
@framework = Framework.find_by_permalink!(params[:framework])
@page_title << @framework.name.downcase
options[:include] << :framework
@query.framework_id_is(@framework.id)
end
if params[:type_id]
@type_id = JOB_LABELS.index(params[:type_id]) || 0
@page_title << JOB_LABELS[@type_id].downcase
@query.type_id_is(@type_id)
end
@jobs = @query.paginate(options)
respond_to do |format|
format.html # index.html.erb
format.rss
format.atom
end
end
def search
@page_title = ["Szukaj oferty"]
@search = Job.active.search(params[:search])
if params[:search]
@page_title = ["Znalezione oferty"]
@jobs = @search.paginate( :page => params[:page],
:per_page => 30,
:order => "created_at DESC, rank DESC" )
end
respond_to do |format|
format.html
format.rss { render :action => "index" }
format.atom { render :action => "index" }
end
end
# GET /jobs/1
# GET /jobs/1.xml
def show
@job = Job.find_by_permalink!(params[:id])
@job.visited_by(request.remote_ip)
@category = @job.category
@page_title = ["oferta pracy IT", @job.category.name.downcase, @job.localization.name.downcase, @job.company_name.downcase, @job.title.downcase]
@tags = WebSiteConfig['website']['tags'].split(',').map(&:strip) + [@job.category.name, @job.localization.name, @job.company_name]
@tags << JOB_LABELS[@job.type_id]
unless @job.framework.nil?
@tags << @job.framework.name
@page_title.insert(1, @job.framework.name)
end
unless @job.language.nil?
@page_title.insert(1, @job.language.name)
@tags << @job.language.name
end
set_meta_tags :keywords => @tags.join(', ')
respond_to do |format|
format.html # show.html.erb
end
end
# GET /jobs/new
# GET /jobs/new.xml
def new
@job = Job.new
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @job }
end
end
# POST /jobs
# POST /jobs.xml
def create
@job = Job.new(params[:job])
respond_to do |format|
if @job.save
flash[:notice] = 'Na twój e-mail zostaÅ wysÅany link którym opublikujesz ofertÄ.'
format.html { redirect_to(@job) }
format.xml { render :xml => @job, :status => :created, :location => @job }
else
format.html { render :action => "new" }
format.xml { render :xml => @job.errors, :status => :unprocessable_entity }
end
end
end
# GET /jobs/1/edit
def edit
@job = Job.find_by_permalink_and_token!(params[:id], params[:token])
render :action => "new"
end
# PUT /jobs/1
# PUT /jobs/1.xml
def update
@job = Job.find_by_permalink_and_token!(params[:id], params[:token])
respond_to do |format|
if @job.update_attributes(params[:job])
flash[:notice] = 'Zapisano zmiany w ofercie.'
format.html { redirect_to(@job) }
format.xml { head :ok }
else
format.html { render :action => "new" }
format.xml { render :xml => @job.errors, :status => :unprocessable_entity }
end
end
end
def publish
@job = Job.find_by_permalink_and_token!(params[:id], params[:token])
unless @job.published
@job.publish!
flash[:notice] = "Twoja oferta jest już widoczna!"
end
redirect_to @job
end
# DELETE /jobs/1
# DELETE /jobs/1.xml
def destroy
@job = Job.find_by_permalink_and_token!(params[:id], params[:token])
@job.destroy
flash[:notice] = "Oferta zostaÅa usuniÄta"
respond_to do |format|
format.html { redirect_to(jobs_url) }
format.xml { head :ok }
end
end
end
diff --git a/app/models/job.rb b/app/models/job.rb
index 0e721f8..8c9d09e 100644
--- a/app/models/job.rb
+++ b/app/models/job.rb
@@ -1,177 +1,177 @@
JOB_TYPES = ["zlecenie (konkretna usÅuga do wykonania)", "poszukiwanie wspóÅpracowników / oferta pracy", "wolontariat (praca za reklamy, bannery, itp. lub praca za darmo)", "staż/praktyka"]
JOB_LABELS = ["zlecenie", "etat", "wolontariat", "praktyka"]
JOB_ETAT = 1;
JOB_RANK_VALUES = {
:default => 0.3,
:price => 0.8,
:krs => 0.6,
:nip => 0.5,
:regon => 0.6,
:framework_id => 0.7,
- :language_id => 0.5,
- :website => 0.3,
- :apply_online => 0.2
+ :language_id => 0.7,
+ :website => 0.4,
+ :apply_online => 0.3
}
class Job < ActiveRecord::Base
include ActionController::UrlWriter
xss_terminate
has_permalink :title
named_scope :active, :conditions => ["((jobs.end_at >= ?) AND (jobs.published = ?))", Date.current, true]
named_scope :old, :conditions => ["jobs.end_at < ?", Date.current]
named_scope :has_text, lambda { |text| { :conditions => ["((jobs.title ILIKE ?) OR (jobs.description ILIKE ?))", "%#{text}%", "%#{text}%"] } }
validates_presence_of :title, :description, :email, :company_name, :localization_id, :category_id
validates_length_of :title, :within => 3..255
validates_length_of :description, :within => 10..5000
validates_inclusion_of :type_id, :in => 0..JOB_TYPES.size-1
validates_inclusion_of :availability_time, :in => 1..60
validates_numericality_of :price_from,
:greater_than => 0,
:unless => Proc.new { |j| j.price_from.nil? }
validates_numericality_of :price_to,
:greater_than => 0,
:unless => Proc.new { |j| j.price_to.nil? }
validates_format_of :email, :with => /([a-z0-9_.-]+)@([a-z0-9-]+)\.([a-z.]+)/i
validates_format_of :website, :with => /(^$)|(^(http|https):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(([0-9]{1,5})?\/.*)?$)/ix
validates_format_of :regon,
:with => /(^$)|(^[0-9]{7,14}$)/
validates_format_of :nip,
:with => /(^$)|(^\d{2,3}-\d{2,3}-\d{2,3}-\d{2,3}$)/
validates_format_of :krs,
:with => /(^$)|(^\d{10})$/
belongs_to :framework
belongs_to :localization
belongs_to :category
belongs_to :language
has_many :applicants, :dependent => :delete_all
has_many :visits, :dependent => :delete_all
attr_protected :rank, :permalink, :end_at, :token, :published
attr_accessor :framework_name, :localization_name
before_create :create_from_name, :generate_token
before_save :calculate_rank
after_create :send_notification
def self.find_grouped_by_type
return Job.active.count(:type_id, :group => "type_id")
end
def send_notification
JobMailer.deliver_job_posted(self)
end
def generate_token
alphanumerics = ('a'..'z').to_a.concat(('A'..'Z').to_a.concat(('0'..'9').to_a))
salt = alphanumerics.sort_by{rand}.to_s[0..1024]
self.token = Digest::SHA1.hexdigest("--#{salt}--#{self.id}--#{Date.current}--")
generate_token unless Job.find_by_token(self.token).nil?
end
def calculate_rank
self.rank = 1.0
self.rank += visits_count * 0.01 unless visits_count.nil?
[:regon, :nip, :krs, :framework_id, :website, :apply_online].each do |attribute|
val = send(attribute)
inc = JOB_RANK_VALUES[attribute] || JOB_RANK_VALUES[:default]
self.rank += inc unless (val.nil? || (val.class == String && val.empty?) || (val.class == TrueClass))
end
if pay_band?
self.rank += JOB_RANK_VALUES[:price]
price = price_from || price_to
if price >= 10_000 # ciekawe czy ktoÅ da tyle :P
self.rank += 0.8
elsif price >= 7000
self.rank += 0.7
elsif price >= 5000
self.rank += 0.6
elsif price >= 3000
self.rank += 0.3
elsif price < 2000
if self.type_id == JOB_ETAT
self.rank -= 0.6 # bo nikt za grosze nie chce pracowaÄ
else
self.rank += 0.3 # chyba że to biedny student
end
end
end
end
def pay_band?
((!self.price_from.nil? && self.price_from > 0) || (!self.price_to.nil? && self.price_to > 0))
end
def create_from_name
unless (self.framework_name.nil? || self.framework_name.blank?)
framework = Framework.name_like(self.framework_name).first
framework = Framework.create(:name => self.framework_name) if framework.nil?
self.framework = framework
end
unless (self.localization_name.nil? || self.localization_name.blank?)
localization = Localization.name_like(self.localization_name).first
localization = Localization.create(:name => self.localization_name) if localization.nil?
self.localization = localization
end
end
def availability_time
date = created_at.nil? ? Date.current.to_date : created_at.to_date
return (read_attribute(:end_at) - date).to_i rescue 14
end
def availability_time=(val)
date = created_at.nil? ? Date.current.to_date : created_at.to_date
write_attribute(:end_at, date+val.to_i.days)
end
def highlighted?
self.rank >= 4.75
end
def publish!
self.published = true
save
tags = [localization.name, category.name, "praca", JOB_LABELS[self.type_id]]
tags << framework.name unless framework.nil?
MicroFeed.send :streams => :all,
:msg => "[#{company_name}] - #{title}",
:tags => tags,
:link => seo_job_url(self, :host => "webpraca.net") if Rails.env == "production"
end
def visited_by(ip)
visit = visits.find_or_create_by_ip(IPAddr.new(ip).to_i)
visits_count += 1 if visit.new_record?
save
end
def to_param
permalink
end
end
|
macbury/webpraca
|
91f7592182f22aa94e586caeb07464c6cb0c4446
|
Language
|
diff --git a/app/controllers/jobs_controller.rb b/app/controllers/jobs_controller.rb
index 0701821..6d67a4b 100644
--- a/app/controllers/jobs_controller.rb
+++ b/app/controllers/jobs_controller.rb
@@ -1,208 +1,222 @@
class JobsController < ApplicationController
validates_captcha :only => [:create, :new]
ads_pos :bottom
ads_pos :right, :except => [:home, :index, :search]
ads_pos :none, :only => [:home]
def widget
@jobs = Job.active.all(:order => "rank DESC, created_at DESC", :limit => 10, :include => [:category, :localization])
@options = {
:width => "270px",
:background => "#FFFFFF",
:border => "#CCCCCC",
}.merge!(params)
@jobs_hash = @jobs.map do |job|
{
:title => job.title,
:id => job.id,
:type => JOB_LABELS[job.type_id],
:category => job.category.name,
:company => job.company_name,
:localization => job.localization.name,
:url => seo_job_url(job)
}
end
respond_to do |format|
format.js
end
end
def home
set_meta_tags :title => 'najpopularniejsze i najnowsze oferty pracy z IT',
:separator => " - "
query = Job.active.search
@recent_jobs = query.all(:order => "created_at DESC", :limit => 10, :include => [:localization, :category])
@top_jobs = query.all(:order => "rank DESC, created_at DESC", :limit => 10, :include => [:localization, :category])
end
# GET /jobs
# GET /jobs.xml
def index
@query = Job.active.search
options = {
:page => params[:page],
:per_page => 25,
:order => "created_at DESC, rank DESC",
:include => [:localization, :category]
}
if params[:order] =~ /najpopularniejsze/i
@page_title = ['najpopularniejsze oferty pracy IT']
@order = :rank
options[:order] = "rank DESC, created_at DESC"
else
@order = :created_at
@page_title = ['najnowsze oferty pracy IT']
options[:order] = "created_at DESC, rank DESC"
end
+ if params[:language]
+ @language = Language.find_by_permalink!(params[:language])
+ @page_title << @language.name.downcase
+ @query.language_id_is(@language.id)
+ end
+
if params[:category]
@category = Category.find_by_permalink!(params[:category])
@page_title << @category.name.downcase
@query.category_id_is(@category.id)
end
if params[:localization]
@localization = Localization.find_by_permalink!(params[:localization])
@page_title << @localization.name.downcase
@query.localization_id_is(@localization.id)
end
if params[:framework]
@framework = Framework.find_by_permalink!(params[:framework])
@page_title << @framework.name.downcase
options[:include] << :framework
@query.framework_id_is(@framework.id)
end
if params[:type_id]
@type_id = JOB_LABELS.index(params[:type_id]) || 0
@page_title << JOB_LABELS[@type_id].downcase
@query.type_id_is(@type_id)
end
@jobs = @query.paginate(options)
respond_to do |format|
format.html # index.html.erb
format.rss
format.atom
end
end
def search
@page_title = ["Szukaj oferty"]
@search = Job.active.search(params[:search])
if params[:search]
@page_title = ["Znalezione oferty"]
@jobs = @search.paginate( :page => params[:page],
:per_page => 30,
:order => "created_at DESC, rank DESC" )
end
respond_to do |format|
format.html
format.rss { render :action => "index" }
format.atom { render :action => "index" }
end
end
# GET /jobs/1
# GET /jobs/1.xml
def show
@job = Job.find_by_permalink!(params[:id])
@job.visited_by(request.remote_ip)
@category = @job.category
+ @page_title = ["oferta pracy IT", @job.category.name.downcase, @job.localization.name.downcase, @job.company_name.downcase, @job.title.downcase]
+
@tags = WebSiteConfig['website']['tags'].split(',').map(&:strip) + [@job.category.name, @job.localization.name, @job.company_name]
- @tags << @job.framework.name unless @job.framework.nil?
@tags << JOB_LABELS[@job.type_id]
+ unless @job.framework.nil?
+ @tags << @job.framework.name
+ @page_title.insert(1, @job.framework.name)
+ end
- set_meta_tags :keywords => @tags.join(', '),
- :title => ["oferta pracy IT", @job.category.name.downcase, @job.localization.name.downcase, @job.company_name.downcase, @job.title.downcase],
- :separator => " - "
+ unless @job.language.nil?
+ @page_title.insert(1, @job.language.name)
+ @tags << @job.language.name
+ end
+
+ set_meta_tags :keywords => @tags.join(', ')
respond_to do |format|
format.html # show.html.erb
end
end
# GET /jobs/new
# GET /jobs/new.xml
def new
@job = Job.new
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @job }
end
end
# POST /jobs
# POST /jobs.xml
def create
@job = Job.new(params[:job])
respond_to do |format|
if @job.save
flash[:notice] = 'Na twój e-mail zostaÅ wysÅany link którym opublikujesz ofertÄ.'
format.html { redirect_to(@job) }
format.xml { render :xml => @job, :status => :created, :location => @job }
else
format.html { render :action => "new" }
format.xml { render :xml => @job.errors, :status => :unprocessable_entity }
end
end
end
# GET /jobs/1/edit
def edit
@job = Job.find_by_permalink_and_token!(params[:id], params[:token])
render :action => "new"
end
# PUT /jobs/1
# PUT /jobs/1.xml
def update
@job = Job.find_by_permalink_and_token!(params[:id], params[:token])
respond_to do |format|
if @job.update_attributes(params[:job])
flash[:notice] = 'Zapisano zmiany w ofercie.'
format.html { redirect_to(@job) }
format.xml { head :ok }
else
format.html { render :action => "new" }
format.xml { render :xml => @job.errors, :status => :unprocessable_entity }
end
end
end
def publish
@job = Job.find_by_permalink_and_token!(params[:id], params[:token])
unless @job.published
@job.publish!
flash[:notice] = "Twoja oferta jest już widoczna!"
end
redirect_to @job
end
# DELETE /jobs/1
# DELETE /jobs/1.xml
def destroy
@job = Job.find_by_permalink_and_token!(params[:id], params[:token])
@job.destroy
flash[:notice] = "Oferta zostaÅa usuniÄta"
respond_to do |format|
format.html { redirect_to(jobs_url) }
format.xml { head :ok }
end
end
end
diff --git a/app/models/job.rb b/app/models/job.rb
index 55d110e..0e721f8 100644
--- a/app/models/job.rb
+++ b/app/models/job.rb
@@ -1,176 +1,177 @@
JOB_TYPES = ["zlecenie (konkretna usÅuga do wykonania)", "poszukiwanie wspóÅpracowników / oferta pracy", "wolontariat (praca za reklamy, bannery, itp. lub praca za darmo)", "staż/praktyka"]
JOB_LABELS = ["zlecenie", "etat", "wolontariat", "praktyka"]
JOB_ETAT = 1;
JOB_RANK_VALUES = {
:default => 0.3,
:price => 0.8,
:krs => 0.6,
:nip => 0.5,
:regon => 0.6,
:framework_id => 0.7,
+ :language_id => 0.5,
:website => 0.3,
:apply_online => 0.2
}
class Job < ActiveRecord::Base
include ActionController::UrlWriter
xss_terminate
has_permalink :title
named_scope :active, :conditions => ["((jobs.end_at >= ?) AND (jobs.published = ?))", Date.current, true]
named_scope :old, :conditions => ["jobs.end_at < ?", Date.current]
named_scope :has_text, lambda { |text| { :conditions => ["((jobs.title ILIKE ?) OR (jobs.description ILIKE ?))", "%#{text}%", "%#{text}%"] } }
validates_presence_of :title, :description, :email, :company_name, :localization_id, :category_id
validates_length_of :title, :within => 3..255
validates_length_of :description, :within => 10..5000
validates_inclusion_of :type_id, :in => 0..JOB_TYPES.size-1
validates_inclusion_of :availability_time, :in => 1..60
validates_numericality_of :price_from,
:greater_than => 0,
:unless => Proc.new { |j| j.price_from.nil? }
validates_numericality_of :price_to,
:greater_than => 0,
:unless => Proc.new { |j| j.price_to.nil? }
validates_format_of :email, :with => /([a-z0-9_.-]+)@([a-z0-9-]+)\.([a-z.]+)/i
validates_format_of :website, :with => /(^$)|(^(http|https):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(([0-9]{1,5})?\/.*)?$)/ix
validates_format_of :regon,
:with => /(^$)|(^[0-9]{7,14}$)/
validates_format_of :nip,
:with => /(^$)|(^\d{2,3}-\d{2,3}-\d{2,3}-\d{2,3}$)/
validates_format_of :krs,
:with => /(^$)|(^\d{10})$/
belongs_to :framework
belongs_to :localization
belongs_to :category
+ belongs_to :language
has_many :applicants, :dependent => :delete_all
has_many :visits, :dependent => :delete_all
attr_protected :rank, :permalink, :end_at, :token, :published
attr_accessor :framework_name, :localization_name
before_create :create_from_name, :generate_token
before_save :calculate_rank
after_create :send_notification
def self.find_grouped_by_type
return Job.active.count(:type_id, :group => "type_id")
end
def send_notification
JobMailer.deliver_job_posted(self)
end
def generate_token
alphanumerics = ('a'..'z').to_a.concat(('A'..'Z').to_a.concat(('0'..'9').to_a))
salt = alphanumerics.sort_by{rand}.to_s[0..1024]
self.token = Digest::SHA1.hexdigest("--#{salt}--#{self.id}--#{Date.current}--")
generate_token unless Job.find_by_token(self.token).nil?
end
def calculate_rank
self.rank = 1.0
self.rank += visits_count * 0.01 unless visits_count.nil?
[:regon, :nip, :krs, :framework_id, :website, :apply_online].each do |attribute|
val = send(attribute)
inc = JOB_RANK_VALUES[attribute] || JOB_RANK_VALUES[:default]
self.rank += inc unless (val.nil? || (val.class == String && val.empty?) || (val.class == TrueClass))
end
if pay_band?
self.rank += JOB_RANK_VALUES[:price]
price = price_from || price_to
if price >= 10_000 # ciekawe czy ktoÅ da tyle :P
self.rank += 0.8
elsif price >= 7000
self.rank += 0.7
elsif price >= 5000
self.rank += 0.6
elsif price >= 3000
self.rank += 0.3
elsif price < 2000
if self.type_id == JOB_ETAT
self.rank -= 0.6 # bo nikt za grosze nie chce pracowaÄ
else
self.rank += 0.3 # chyba że to biedny student
end
end
end
end
def pay_band?
((!self.price_from.nil? && self.price_from > 0) || (!self.price_to.nil? && self.price_to > 0))
end
def create_from_name
unless (self.framework_name.nil? || self.framework_name.blank?)
framework = Framework.name_like(self.framework_name).first
framework = Framework.create(:name => self.framework_name) if framework.nil?
self.framework = framework
end
unless (self.localization_name.nil? || self.localization_name.blank?)
localization = Localization.name_like(self.localization_name).first
localization = Localization.create(:name => self.localization_name) if localization.nil?
self.localization = localization
end
end
def availability_time
date = created_at.nil? ? Date.current.to_date : created_at.to_date
return (read_attribute(:end_at) - date).to_i rescue 14
end
def availability_time=(val)
date = created_at.nil? ? Date.current.to_date : created_at.to_date
write_attribute(:end_at, date+val.to_i.days)
end
def highlighted?
self.rank >= 4.75
end
def publish!
self.published = true
save
- spawn do
- tags = [localization.name, category.name, "praca", JOB_LABELS[self.type_id]]
- tags << framework.name unless framework.nil?
-
- MicroFeed.send :streams => :all,
- :msg => "[#{company_name}] - #{title}",
- :tags => tags,
- :link => seo_job_url(self, :host => "webpraca.net")
- end
+ tags = [localization.name, category.name, "praca", JOB_LABELS[self.type_id]]
+ tags << framework.name unless framework.nil?
+
+ MicroFeed.send :streams => :all,
+ :msg => "[#{company_name}] - #{title}",
+ :tags => tags,
+ :link => seo_job_url(self, :host => "webpraca.net") if Rails.env == "production"
+
end
def visited_by(ip)
visit = visits.find_or_create_by_ip(IPAddr.new(ip).to_i)
visits_count += 1 if visit.new_record?
save
end
def to_param
permalink
end
end
diff --git a/app/models/language.rb b/app/models/language.rb
new file mode 100644
index 0000000..5902e13
--- /dev/null
+++ b/app/models/language.rb
@@ -0,0 +1,18 @@
+class Language < ActiveRecord::Base
+ has_many :jobs, :dependent => :delete_all
+ xss_terminate
+ has_permalink :name
+
+ def to_param
+ permalink
+ end
+
+ def self.find_job_languages
+ return Language.all(
+ :select => "count(jobs.language_id) as jobs_count, languages.*",
+ :conditions => ["((jobs.end_at >= ?) AND (jobs.published = ?))", Date.current, true],
+ :joins => :jobs,
+ :group => Language.column_names.map{|c| "languages.#{c}"}.join(','),
+ :order => "languages.name")
+ end
+end
diff --git a/app/views/admin/jobs/index.html.erb b/app/views/admin/jobs/index.html.erb
index eeb9a90..84178c4 100644
--- a/app/views/admin/jobs/index.html.erb
+++ b/app/views/admin/jobs/index.html.erb
@@ -1,39 +1,42 @@
<div class="box">
<div>
<div class="title">
<h2>Oferty</h2>
</div>
<table>
<thead>
<tr>
<th>Nazwa</th>
<th width="130px" class="text_center">Dodano</th>
<th width="100px" class="text_center">Edycja</th>
</tr>
</thead>
<% if @jobs.nil? || @jobs.empty? %>
<tr>
<td colspan="2" class="info">
Brak ofert!
</td>
</tr>
<% else %>
<% @jobs.each do |job| %>
<tr class="<%= cycle('normal', 'alt') %>">
<td><%= link_to job.title, seo_job_path(job) %></td>
<td class="text_center">
<%= l job.created_at, :format => :long %>
</td>
<td class="text_center">
+ <% unless job.published %>
+ <%= link_to "Publikuj", publish_job_path(job, :token => job.token) %>
+ <% end %>
<%= link_to 'Edytuj', edit_admin_job_path(job) %> |
<%= link_to 'UsuÅ', admin_job_path(job), :confirm => 'Czy na pewno chcesz usunÄ
Ä ofertÄ?', :method => :delete %>
</td>
</tr>
<% end %>
<% end %>
</table>
<%= will_paginate @jobs %>
</div>
</div>
\ No newline at end of file
diff --git a/app/views/jobs/_form.html.erb b/app/views/jobs/_form.html.erb
index 8318142..9b76059 100644
--- a/app/views/jobs/_form.html.erb
+++ b/app/views/jobs/_form.html.erb
@@ -1,59 +1,60 @@
<%= hidden_field_tag 'token', params[:token] unless params[:token].nil? %>
<% form.inputs :name => 'SzczegóÅy oferty pracy' do %>
<%= form.input :title %>
<%= form.input :category_id, :as => :select, :collection => Category.all.map { |c| [c.name, c.id] } %>
<li class="select">
<%= form.label :localization_id, 'Lokalizacja*' %>
<%= form.select :localization_id, Localization.all(:order => 'name').map { |localization| [localization.name, localization.id] } %> albo
<%= form.text_field :localization_name %>
<p class="inline-hints">np. 'Warszawa', 'Kraków, UK'</p>
<%= inline_errors @job, :localization_name %>
</li>
<%= form.input :type_id, :as => :radio, :collection => collection_from_types(JOB_TYPES) %>
<%= form.input :remote_job, :required => false %>
<%= form.input :availability_time, :as => :numeric, :hint => "ile dni oferta ma byÄ ważna(od 1 do 60 dni)" %>
+ <%= form.input :language, :collection => Language.all(:order => 'name').map { |l| [l.name, l.id] }, :include_blank => true, :required => false %>
<li class="select">
<%= form.label :framework_id, 'Framework' %>
<%= form.select :framework_id, Framework.all(:order => 'name').map { |frame| [frame.name, frame.id] }, :include_blank => true %> albo
<%= form.text_field :framework_name %>
<p class="inline-hints">gÅówny framework którego znajomoÅÄ jest wymagana, podaj peÅnÄ
nazwÄ</p>
<%= inline_errors @job, :framework_name %>
</li>
<li class="numeric prices">
<label>WideÅki zarobkowe:</label>
<%= form.text_field :price_from %> do <%= form.text_field :price_to %> PLN na miesiÄ
c, netto
<%= inline_errors @job, :price_from %>
<%= inline_errors @job, :price_to %>
</li>
<li>
<%= form.label :description, 'Opis*' %>
<%= form.text_area :description %>
<%= inline_errors @job, :description %>
</li>
<% end %>
<% form.inputs :name => "Aplikuj online" do %>
<%= form.input :apply_online, :required => false, :hint => "uaktywnia formularz umożliwiajÄ
cy przesyÅanie aplikacji online w ofercie" %>
<%= form.input :email_title, :required => false, :hint => "np. MÅodszy programista, Ruby Developer/18/12/71 itp" %>
<% end %>
<% form.inputs :name => 'Firma zatrudniajÄ
ca lub osoba zlecajÄ
ca' do %>
<%= form.input :email, :hint => "Pod wskazany adres zostanÄ
przesÅane linki do edycji oferty, nie bÄdzie on widoczny publicznie(zamiast niego bÄdzie dostÄpny formularz kontaktowy)." %>
<%= form.input :company_name %>
<%= form.input :website, :hint => "zaczynajÄ
cy siÄ od http://", :required => false %>
<%= form.input :nip, :required => false %>
<%= form.input :regon, :required => false %>
<%= form.input :krs, :required => false %>
<% end %>
<% if @job.new_record? %>
<% form.inputs :name => "Czy jesteÅ czÅowiekiem" do %>
<li class="string required">
<%= form.label :captcha, 'Kod z obrazka*' %>
<%= form.captcha_challenge %>
<%= form.captcha_field %>
<%= inline_errors @job, :captcha_solution %>
</li>
<% end %>
<% end %>
\ No newline at end of file
diff --git a/app/views/jobs/_sidebar.html.erb b/app/views/jobs/_sidebar.html.erb
index 72bce96..6f79d28 100644
--- a/app/views/jobs/_sidebar.html.erb
+++ b/app/views/jobs/_sidebar.html.erb
@@ -1,42 +1,56 @@
<div class="box">
<div>
<div class="title"><h3>typ</h3></div>
<ul class="list">
<% Job.find_grouped_by_type.each do | type_id, jobs_count | %>
<li class="<%= cycle('normal', 'alt') %>">
<span class="badge"><%= jobs_count %></span>
<%= link_to JOB_LABELS[type_id], job_type_path(JOB_LABELS[type_id]) , :class => "etykieta #{JOB_LABELS[type_id]}"%>
</li>
<% end %>
</ul>
<div class="clear"></div>
</div>
<div>
<div class="title">
<h3>lokalizacje</h3>
</div>
<ul class="list">
<% for place in Localization.find_job_localizations %>
<li class="<%= cycle('normal', 'alt') %>">
<span class="badge"><%= place.jobs_count %></span>
<%= link_to place.name, localization_path(place.permalink) %>
</li>
<% end %>
</ul>
</div>
+ <div>
+ <div class="title">
+ <h3>jÄzyk</h3>
+ </div>
+ <ul class="list">
+ <% for language in Language.find_job_languages %>
+ <li class="<%= cycle('normal', 'alt') %>">
+ <span class="badge"><%= language.jobs_count %></span>
+ <%= link_to language.name, language_path(language) %>
+ </li>
+ <% end %>
+ </ul>
+ </div>
+
<div>
<div class="title">
<h3>frameworki</h3>
</div>
<ul class="list">
<% for framework in Framework.find_job_frameworks %>
<li class="<%= cycle('normal', 'alt') %>">
<span class="badge"><%= framework.jobs_count %></span>
<%= link_to framework.name, framework_path(framework.permalink) %>
</li>
<% end %>
</ul>
</div>
</div>
diff --git a/app/views/jobs/show.html.erb b/app/views/jobs/show.html.erb
index d3b61eb..5041a41 100644
--- a/app/views/jobs/show.html.erb
+++ b/app/views/jobs/show.html.erb
@@ -1,84 +1,88 @@
<div class="box">
<div>
<div class="title">
<h2>
<%= @job.title %>
</h2>
</div>
<dl>
<dt>Typ</dt>
<dd><%= job_label(@job) %></dd>
<dt>Kategoria</dt>
<dd><%= link_to @job.category.name, job_category_path(@job.category) %></dd>
<dt>Ocena</dt>
<dd><%= format_rank(@job.rank) %></dd>
<dt>Pracodawca</dt>
<dd><%= link_to @job.company_name, @job.website, :target => "_blank" %></dd>
<dt>Lokalizacja</dt>
<dd><%= link_to @job.localization.name, localization_path(@job.localization) %></dd>
<% unless @job.framework.nil? %>
<dt>Framework</dt>
<dd><%= link_to @job.framework.name, framework_path(@job.framework) %></dd>
<% end %>
+ <% unless @job.language.nil? %>
+ <dt>JÄzyk</dt>
+ <dd><%= link_to @job.language.name, language_path(@job.language) %></dd>
+ <% end %>
<% if @job.pay_band? %>
<dt>WideÅko zarobkowe</dt>
<dd>
<%= "od #{number_to_currency(@job.price_from)}" unless @job.price_from.nil? %>
<%= "do #{number_to_currency(@job.price_to)}" unless @job.price_to.nil? %> na miesiÄ
c, netto
</dd>
<% end %>
<% unless @job.apply_online %>
<dt>Kontakt</dt>
<dd><%= link_to "Formularz kontaktowy", contact_path(:job_id => @job.id) %></dd>
<% end %>
<% unless (@job.regon.nil? || @job.regon.empty?) %>
<dt>REGON</dt>
<dd><%= @job.regon %> </dd>
<% end %>
<% unless (@job.nip.nil? || @job.nip.empty?) %>
<dt>NIP</dt>
<dd><%= @job.nip %> </dd>
<% end %>
<% unless (@job.krs.nil? || @job.krs.empty?) %>
<dt>KRS</dt>
<dd><%= link_to @job.krs, "http://krs.ms.gov.pl/Podmiot.aspx?nrkrs=#{@job.krs}", :target => "_blank" %> </dd>
<% end %>
<dt>Data rozpoczÄcia</dt>
<dd>
<%= l @job.created_at, :format => :long %>
<br />
<abbr title="<%= @job.created_at.xmlschema %>"><%= distance_of_time_in_words_to_now @job.created_at %> temu</abbr>
</dd>
<dt>Data zakoÅczenia</dt>
<dd>
<%= l @job.end_at, :format => :long %>
<br />
za <abbr title="<%= @job.end_at.xmlschema %>"><%= distance_of_time_in_words_to_now(@job.end_at) %></abbr>
</dd>
<dt>WyÅwietlona</dt>
<dd><%= @job.visits_count %> razy</dd>
</dl>
<div class="clear"></div>
</div>
<div>
<div class="title mini">
<h3>Opis oferty</h3>
</div>
<div class="text">
<%= RedCloth.new(highlight(@job.description, @tags, :highlighter => '<i>\1</i>')).to_html %>
</div>
<p>
<% if permitted_to? :edit, @job %>
<%= link_to 'Edytuj', edit_job_path(@job) %> |
<%= link_to 'Wstecz', jobs_path %>
<% end %>
</p>
</div>
<%= link_to 'Aplikuj online!', new_job_applicant_path(@job), :class => "more" if @job.apply_online %>
</div>
diff --git a/config/locales/pl.yml b/config/locales/pl.yml
index ebb5875..583a439 100644
--- a/config/locales/pl.yml
+++ b/config/locales/pl.yml
@@ -1,175 +1,176 @@
# Polish translations for Ruby on Rails
# by Jacek Becela (jacek.becela@gmail.com, http://github.com/ncr)
pl:
number:
format:
separator: ","
delimiter: " "
precision: 2
currency:
format:
format: "%n %u"
unit: "PLN"
percentage:
format:
delimiter: ""
precision:
format:
delimiter: ""
human:
format:
delimiter: ""
precision: 1
storage_units:
format: "%n %u"
units:
byte:
one: "bajt"
other: "bajty"
kb: "KB"
mb: "MB"
gb: "GB"
tb: "TB"
date:
formats:
default: "%Y-%m-%d"
short: "%d %b"
school: "%Y"
simple: "%d.%m.%Y"
long: "%d %B %Y"
day_names: [Niedziela, PoniedziaÅek, Wtorek, Åroda, Czwartek, PiÄ
tek, Sobota]
abbr_day_names: [nie, pon, wto, Åro, czw, pia, sob]
month_names: [~, StyczeÅ, Luty, Marzec, KwiecieÅ, Maj, Czerwiec, Lipiec, SierpieÅ, WrzesieÅ, Październik, Listopad, GrudzieÅ]
abbr_month_names: [~, sty, lut, mar, kwi, maj, cze, lip, sie, wrz, paź, lis, gru]
order: [ :year, :month, :day ]
time:
formats:
default: "%a, %d %b %Y, %H:%M:%S %z"
short: "%d %b, %H:%M"
long: "%d %B %Y, %H:%M"
am: "przed poÅudniem"
pm: "po poÅudniu"
datetime:
distance_in_words:
half_a_minute: "póŠminuty"
less_than_x_seconds:
one: "mniej niż sekundÄ"
few: "mniej niż {{count}} sekundy"
other: "mniej niż {{count}} sekund"
x_seconds:
one: "sekundÄ"
few: "{{count}} sekundy"
other: "{{count}} sekund"
less_than_x_minutes:
one: "mniej niż minutÄ"
few: "mniej niż {{count}} minuty"
other: "mniej niż {{count}} minut"
x_minutes:
one: "minutÄ"
few: "{{count}} minuty"
other: "{{count}} minut"
about_x_hours:
one: "okoÅo godziny"
other: "okoÅo {{count}} godzin"
x_days:
one: "1 dzieÅ"
other: "{{count}} dni"
about_x_months:
one: "okoÅo miesiÄ
ca"
other: "okoÅo {{count}} miesiÄcy"
x_months:
one: "1 miesiÄ
c"
few: "{{count}} miesiÄ
ce"
other: "{{count}} miesiÄcy"
about_x_years:
one: "okoÅo roku"
other: "okoÅo {{count}} lat"
over_x_years:
one: "ponad rok"
few: "ponad {{count}} lata"
other: "ponad {{count}} lat"
activerecord:
models:
user: "Użytkownik"
job: "Praca"
search: "Wyszukiwarka"
applicant: "Aplikant"
comment:
attributes:
captcha_solution:
blank: 'musi byÄ podane'
invalid: 'odpowiedź jest niepoprawna'
attributes:
websiteconfig:
groups:
website: "Strona WWW"
js: "Skrypty"
js:
google_analytics: "Google Analytics"
widget: "Reklama"
website:
name: "Nazwa"
tags: "SÅowa kluczowe"
description: "Opis"
applicant:
email: "Twój E-Mail"
body: "TreÅÄ"
cv: "Dodaj ofertÄ/CV"
job:
title: "TytuÅ"
place_id: "Lokalizacja"
description: "Opis"
availability_time: "DÅugoÅÄ trwania"
remote_job: "Praca zdalna"
type_id: "Typ"
category_id: "Kategoria"
company_name: "Nazwa"
website: "Strona WWW"
framework_name: "Framework"
apply_online: "Aplikuj online"
email_title: "TytuÅ emaila"
+ language: "JÄzyk"
user:
password: "HasÅo"
password_confirmation: "Powtórz hasÅo"
errors:
template:
header:
one: "{{model}} nie zostaÅ zachowany z powodu jednego bÅÄdu"
other: "{{model}} nie zostaÅ zachowany z powodu {{count}} bÅÄdów"
body: "BÅÄdy dotyczÄ
nastÄpujÄ
cych pól:"
messages:
inclusion: "nie znajduje siÄ na liÅcie dopuszczalnych wartoÅci"
exclusion: "znajduje siÄ na liÅcie zabronionych wartoÅci"
invalid: "jest nieprawidÅowe"
confirmation: "nie zgadza siÄ z potwierdzeniem"
accepted: "musi byÄ zaakceptowane"
empty: "nie może byÄ puste"
blank: "nie może byÄ puste"
too_long: "jest za dÅugie (maksymalnie {{count}} znaków)"
too_short: "jest za krótkie (minimalnie {{count}} znaków)"
wrong_length: "jest nieprawidÅowej dÅugoÅci (powinna wynosiÄ {{count}} znaków)"
taken: "zostaÅo już zajÄte"
not_a_number: "nie jest liczbÄ
"
greater_than: "musi byÄ wiÄksze niż {{count}}"
greater_than_or_equal_to: "musi byÄ wiÄksze lub równe {{count}}"
equal_to: "musi byÄ równe {{count}}"
less_than: "musi byÄ mniejsze niż {{count}}"
less_than_or_equal_to: "musi byÄ mniejsze lub równe {{count}}"
odd: "musi byÄ nieparzyste"
even: "musi byÄ parzyste"
record_invalid: "nieprawidÅowe dane"
support:
array:
sentence_connector: "i"
skip_last_comma: true
words_connector: ", "
two_words_connector: " i "
last_word_connector: " oraz "
diff --git a/config/routes.rb b/config/routes.rb
index 3fd543d..50d551d 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -1,87 +1,89 @@
ActionController::Routing::Routes.draw do |map|
map.new_contact '/contact/new', :controller => 'contact', :action => 'new', :conditions => { :method => :get }
map.contact '/contact', :controller => 'contact', :action => 'new', :conditions => { :method => :get }
map.contact '/contact', :controller => 'contact', :action => 'create', :conditions => { :method => :post }
map.seo_page '/strona/:id/', :controller => 'admin/pages', :action => 'show'
map.with_options :controller => 'jobs', :action => 'index' do |job|
job.with_options :category => nil, :page => 1, :order => "najnowsze", :requirements => { :order => /(najnowsze|najpopularniejsze)/, :page => /\d/ } do |seo|
seo.connect '/oferty/:page'
seo.connect '/oferty/:order'
seo.connect '/oferty/:order/:page'
seo.seo_jobs '/oferty/:order/:category/:page'
end
job.connect '/lokalizacja/:localization/:page'
job.localization '/lokalizacja/:localization'
job.connect '/framework/:framework/:page'
job.framework '/framework/:framework'
+ job.connect '/jezyk/:language/:page'
+ job.language '/jezyk/:language'
job.connect '/typ/:type_id/:page'
job.job_type '/typ/:type_id'
job.connect '/kategoria/:category/:page'
job.job_category '/kategoria/:category'
end
map.resources :jobs, :member => { :publish => :get, :destroy => :any }, :collection => { :search => :any, :widget => :get } do |jobs|
jobs.resources :applicants, :member => { :download => :get }
end
map.resources :user_sessions
map.login '/login', :controller => 'user_sessions', :action => 'new'
map.logout '/logout', :controller => 'user_sessions', :action => 'destroy'
map.namespace :admin do |admin|
admin.stats '/stats', :controller => "stats"
admin.config '/config', :controller => "configs", :action => "new"
admin.resources :pages
admin.resources :jobs
admin.resource :configs
admin.resources :frameworks
admin.resources :categories, :collection => { :reorder => :post }
end
map.admin '/admin', :controller => "admin/stats"
# The priority is based upon order of creation: first created -> highest priority.
# Sample of regular route:
# map.connect 'products/:id', :controller => 'catalog', :action => 'view'
# Keep in mind you can assign values other than :controller and :action
# Sample of named route:
# map.purchase 'products/:id/purchase', :controller => 'catalog', :action => 'purchase'
# This route can be invoked with purchase_url(:id => product.id)
# Sample resource route (maps HTTP verbs to controller actions automatically):
# map.resources :products
# Sample resource route with options:
# map.resources :products, :member => { :short => :get, :toggle => :post }, :collection => { :sold => :get }
# Sample resource route with sub-resources:
# map.resources :products, :has_many => [ :comments, :sales ], :has_one => :seller
# Sample resource route with more complex sub-resources
# map.resources :products do |products|
# products.resources :comments
# products.resources :sales, :collection => { :recent => :get }
# end
# Sample resource route within a namespace:
# map.namespace :admin do |admin|
# # Directs /admin/products/* to Admin::ProductsController (app/controllers/admin/products_controller.rb)
# admin.resources :products
# end
map.root :controller => "jobs", :action => "home"
map.seo_job '/:id', :controller => 'jobs', :action => 'show'
# You can have the root of your site routed with map.root -- just remember to delete public/index.html.
# See how all your routes lay out with "rake routes"
# Install the default routes as the lowest priority.
# Note: These default routes make all actions in every controller accessible via GET requests. You should
# consider removing or commenting them out if you're using named routes and resources.
map.connect ':controller/:action/:id'
map.connect ':controller/:action/:id.:format'
end
diff --git a/config/sitemap.rb b/config/sitemap.rb
index 4050c79..69522d0 100644
--- a/config/sitemap.rb
+++ b/config/sitemap.rb
@@ -1,56 +1,61 @@
# Set the host name for URL creation
SitemapGenerator::Sitemap.default_host = "http://webpraca.net"
SitemapGenerator::Sitemap.add_links do |sitemap|
# Put links creation logic here.
#
# The root path '/' and sitemap index file are added automatically.
# Links are added to the Sitemap in the order they are specified.
#
# Usage: sitemap.add path, options
# (default options are used if you don't specify)
#
# Defaults: :priority => 0.5, :changefreq => 'weekly',
# :lastmod => Time.now, :host => default_host
# Examples:
# add '/articles'
sitemap.add jobs_path, :priority => 1.0, :changefreq => 'daily'
# add all individual articles
Job.active.each do |o|
sitemap.add seo_job_path(o), :lastmod => o.updated_at
end
Framework.all.each do |f|
latest_job = f.jobs.first(:order => "created_at DESC")
sitemap.add framework_path(f), :lastmod => latest_job.nil? ? f.created_at : latest_job.created_at
end
Localization.all.each do |l|
latest_job = l.jobs.first(:order => "created_at DESC")
sitemap.add localization_path(l), :lastmod => latest_job.nil? ? l.created_at : latest_job.created_at
end
Category.all.each do |c|
latest_job = c.jobs.first(:order => "created_at DESC")
sitemap.add job_category_path(c), :lastmod => latest_job.nil? ? c.created_at : latest_job.created_at
end
+ Language.all.each do |l|
+ latest_job = l.jobs.first(:order => "created_at DESC")
+ sitemap.add language_path(l), :lastmod => latest_job.nil? ? l.created_at : latest_job.created_at
+ end
+
Page.all.each do |page|
sitemap.add seo_page_path(page), :lastmod => page.updated_at
end
end
# Including Sitemaps from Rails Engines.
#
# These Sitemaps should be almost identical to a regular Sitemap file except
# they needn't define their own SitemapGenerator::Sitemap.default_host since
# they will undoubtedly share the host name of the application they belong to.
#
# As an example, say we have a Rails Engine in vendor/plugins/cadability_client
# We can include its Sitemap here as follows:
#
# file = File.join(Rails.root, 'vendor/plugins/cadability_client/config/sitemap.rb')
# eval(open(file).read, binding, file)
\ No newline at end of file
diff --git a/db/migrate/20100109211453_create_languages.rb b/db/migrate/20100109211453_create_languages.rb
new file mode 100644
index 0000000..662f34d
--- /dev/null
+++ b/db/migrate/20100109211453_create_languages.rb
@@ -0,0 +1,16 @@
+class CreateLanguages < ActiveRecord::Migration
+ def self.up
+ create_table :languages do |t|
+ t.string :name
+ t.string :permalink
+
+ t.timestamps
+ end
+
+ add_column :jobs, :language_id, :integer
+ end
+
+ def self.down
+ drop_table :languages
+ end
+end
diff --git a/db/schema.rb b/db/schema.rb
index 0d14fbf..ffdd342 100644
--- a/db/schema.rb
+++ b/db/schema.rb
@@ -1,127 +1,141 @@
# This file is auto-generated from the current state of the database. Instead of editing this file,
# please use the migrations feature of Active Record to incrementally modify your database, and
# then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your database schema. If you need
# to create the application database on another system, you should be using db:schema:load, not running
# all the migrations from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended to check this file into your version control system.
-ActiveRecord::Schema.define(:version => 20100105185950) do
+ActiveRecord::Schema.define(:version => 20100109211453) do
create_table "applicants", :force => true do |t|
t.string "email"
t.text "body"
t.integer "job_id"
t.datetime "created_at"
t.datetime "updated_at"
t.string "cv_file_name"
t.string "cv_content_type"
t.integer "cv_file_size"
t.datetime "cv_updated_at"
t.string "token"
end
create_table "assignments", :force => true do |t|
t.integer "user_id"
t.integer "role_id"
t.datetime "created_at"
t.datetime "updated_at"
end
+ create_table "brain_busters", :force => true do |t|
+ t.string "question"
+ t.string "answer"
+ end
+
create_table "categories", :force => true do |t|
t.string "name"
t.string "permalink"
t.integer "position", :default => 0
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "frameworks", :force => true do |t|
t.string "name"
t.string "permalink"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "jobs", :force => true do |t|
t.integer "type_id", :default => 0
t.integer "price_from"
t.integer "price_to"
t.boolean "remote_job"
t.string "title"
t.string "permalink"
t.text "description"
t.date "end_at"
t.string "company_name"
t.string "website"
t.integer "localization_id"
t.string "nip"
t.string "regon"
t.string "krs"
t.string "email"
t.datetime "created_at"
t.datetime "updated_at"
t.integer "framework_id"
t.float "rank"
t.string "token"
t.boolean "published"
t.integer "visits_count", :default => 0
t.boolean "apply_online", :default => true
t.integer "applicants_count", :default => 0
t.integer "category_id"
t.string "email_title"
+ t.integer "language_id"
+ end
+
+ create_table "languages", :force => true do |t|
+ t.string "name"
+ t.string "permalink"
+ t.datetime "created_at"
+ t.datetime "updated_at"
end
create_table "localizations", :force => true do |t|
t.string "name"
t.string "permalink"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "pages", :force => true do |t|
t.string "name"
t.string "permalink"
t.text "body"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "roles", :force => true do |t|
t.string "name"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "users", :force => true do |t|
t.string "login"
t.string "email", :null => false
t.string "crypted_password", :null => false
t.string "password_salt", :null => false
t.string "persistence_token", :null => false
t.integer "login_count", :default => 0, :null => false
t.datetime "last_request_at"
t.datetime "last_login_at"
t.datetime "current_login_at"
t.string "last_login_ip"
t.string "current_login_ip"
t.datetime "created_at"
t.datetime "updated_at"
+ t.integer "visits_count", :default => 0
end
add_index "users", ["email"], :name => "index_users_on_email"
add_index "users", ["last_request_at"], :name => "index_users_on_last_request_at"
add_index "users", ["login"], :name => "index_users_on_login"
add_index "users", ["persistence_token"], :name => "index_users_on_persistence_token"
create_table "visits", :force => true do |t|
t.integer "job_id"
t.datetime "created_at"
t.datetime "updated_at"
t.integer "ip", :limit => 8
end
end
diff --git a/db/seeds.rb b/db/seeds.rb
index 2a525a6..8db81df 100644
--- a/db/seeds.rb
+++ b/db/seeds.rb
@@ -1,19 +1,23 @@
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
#
# Examples:
#
# cities = City.create([{ :name => 'Chicago' }, { :name => 'Copenhagen' }])
# Major.create(:name => 'Daley', :city => cities.first)
['Ruby On Rails', 'Merb', 'Django', 'ASP .NET', 'Sinatra', 'Pylons', 'Symfony', 'CakePHP', 'Kohana', 'Spring', 'Struts', 'LifeRay'].each do |name|
Framework.find_or_create_by_name(name)
end
['Warszawa', 'Kraków', 'GdaÅsk', 'Radom', 'Kielce', 'Lublin', 'Åódź', 'Gdynia', 'ToruÅ'].each do |name|
Localization.find_or_create_by_name(name)
end
['Programowanie', 'Grafika', 'Administracja', 'ZarzÄ
dzanie'].each do |name|
Category.find_or_create_by_name(name)
+end
+
+["Ruby", "Python", "Java", "PHP", "C++", "C", "Objective-C", "C#", "Javascript", "CSS/HTML", "ActionScript", "Perl", "Bash", "Erlang", "SQL", "Scala"].each do |name|
+ Language.find_or_create_by_name(name)
end
\ No newline at end of file
diff --git a/test/fixtures/languages.yml b/test/fixtures/languages.yml
new file mode 100644
index 0000000..88a5970
--- /dev/null
+++ b/test/fixtures/languages.yml
@@ -0,0 +1,9 @@
+# Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html
+
+one:
+ name: MyString
+ permalink: MyString
+
+two:
+ name: MyString
+ permalink: MyString
diff --git a/test/unit/language_test.rb b/test/unit/language_test.rb
new file mode 100644
index 0000000..a366793
--- /dev/null
+++ b/test/unit/language_test.rb
@@ -0,0 +1,8 @@
+require 'test_helper'
+
+class LanguageTest < ActiveSupport::TestCase
+ # Replace this with your real tests.
+ test "the truth" do
+ assert true
+ end
+end
|
macbury/webpraca
|
c65274ac6de7c25c45e98d08fcc3cc3597e8b00c
|
More seo
|
diff --git a/app/controllers/jobs_controller.rb b/app/controllers/jobs_controller.rb
index 4d74b41..0701821 100644
--- a/app/controllers/jobs_controller.rb
+++ b/app/controllers/jobs_controller.rb
@@ -1,204 +1,208 @@
class JobsController < ApplicationController
validates_captcha :only => [:create, :new]
ads_pos :bottom
ads_pos :right, :except => [:home, :index, :search]
ads_pos :none, :only => [:home]
def widget
@jobs = Job.active.all(:order => "rank DESC, created_at DESC", :limit => 10, :include => [:category, :localization])
@options = {
:width => "270px",
:background => "#FFFFFF",
:border => "#CCCCCC",
}.merge!(params)
@jobs_hash = @jobs.map do |job|
{
:title => job.title,
:id => job.id,
:type => JOB_LABELS[job.type_id],
:category => job.category.name,
:company => job.company_name,
:localization => job.localization.name,
:url => seo_job_url(job)
}
end
respond_to do |format|
format.js
end
end
def home
- @page_title = ['najpopularniejsze oferty', 'najnowsze oferty']
+ set_meta_tags :title => 'najpopularniejsze i najnowsze oferty pracy z IT',
+ :separator => " - "
query = Job.active.search
@recent_jobs = query.all(:order => "created_at DESC", :limit => 10, :include => [:localization, :category])
@top_jobs = query.all(:order => "rank DESC, created_at DESC", :limit => 10, :include => [:localization, :category])
end
# GET /jobs
# GET /jobs.xml
def index
@query = Job.active.search
options = {
:page => params[:page],
:per_page => 25,
:order => "created_at DESC, rank DESC",
:include => [:localization, :category]
}
if params[:order] =~ /najpopularniejsze/i
- @page_title = ['Najpopularniejsze oferty pracy']
+ @page_title = ['najpopularniejsze oferty pracy IT']
@order = :rank
options[:order] = "rank DESC, created_at DESC"
else
@order = :created_at
- @page_title = ['Najnowsze oferty pracy']
+ @page_title = ['najnowsze oferty pracy IT']
options[:order] = "created_at DESC, rank DESC"
end
if params[:category]
@category = Category.find_by_permalink!(params[:category])
- @page_title << @category.name
+ @page_title << @category.name.downcase
@query.category_id_is(@category.id)
end
if params[:localization]
@localization = Localization.find_by_permalink!(params[:localization])
- @page_title << @localization.name
+ @page_title << @localization.name.downcase
@query.localization_id_is(@localization.id)
end
if params[:framework]
@framework = Framework.find_by_permalink!(params[:framework])
- @page_title << @framework.name
+ @page_title << @framework.name.downcase
options[:include] << :framework
@query.framework_id_is(@framework.id)
end
if params[:type_id]
@type_id = JOB_LABELS.index(params[:type_id]) || 0
- @page_title << JOB_LABELS[@type_id]
+ @page_title << JOB_LABELS[@type_id].downcase
@query.type_id_is(@type_id)
end
@jobs = @query.paginate(options)
respond_to do |format|
format.html # index.html.erb
format.rss
format.atom
end
end
def search
@page_title = ["Szukaj oferty"]
@search = Job.active.search(params[:search])
if params[:search]
@page_title = ["Znalezione oferty"]
@jobs = @search.paginate( :page => params[:page],
:per_page => 30,
:order => "created_at DESC, rank DESC" )
end
respond_to do |format|
format.html
format.rss { render :action => "index" }
format.atom { render :action => "index" }
end
end
# GET /jobs/1
# GET /jobs/1.xml
def show
@job = Job.find_by_permalink!(params[:id])
@job.visited_by(request.remote_ip)
@category = @job.category
@tags = WebSiteConfig['website']['tags'].split(',').map(&:strip) + [@job.category.name, @job.localization.name, @job.company_name]
@tags << @job.framework.name unless @job.framework.nil?
@tags << JOB_LABELS[@job.type_id]
- set_meta_tags :keywords => @tags.join(', ')
+
+ set_meta_tags :keywords => @tags.join(', '),
+ :title => ["oferta pracy IT", @job.category.name.downcase, @job.localization.name.downcase, @job.company_name.downcase, @job.title.downcase],
+ :separator => " - "
respond_to do |format|
format.html # show.html.erb
end
end
# GET /jobs/new
# GET /jobs/new.xml
def new
@job = Job.new
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @job }
end
end
# POST /jobs
# POST /jobs.xml
def create
@job = Job.new(params[:job])
respond_to do |format|
if @job.save
flash[:notice] = 'Na twój e-mail zostaÅ wysÅany link którym opublikujesz ofertÄ.'
format.html { redirect_to(@job) }
format.xml { render :xml => @job, :status => :created, :location => @job }
else
format.html { render :action => "new" }
format.xml { render :xml => @job.errors, :status => :unprocessable_entity }
end
end
end
# GET /jobs/1/edit
def edit
@job = Job.find_by_permalink_and_token!(params[:id], params[:token])
render :action => "new"
end
# PUT /jobs/1
# PUT /jobs/1.xml
def update
@job = Job.find_by_permalink_and_token!(params[:id], params[:token])
respond_to do |format|
if @job.update_attributes(params[:job])
flash[:notice] = 'Zapisano zmiany w ofercie.'
format.html { redirect_to(@job) }
format.xml { head :ok }
else
format.html { render :action => "new" }
format.xml { render :xml => @job.errors, :status => :unprocessable_entity }
end
end
end
def publish
@job = Job.find_by_permalink_and_token!(params[:id], params[:token])
unless @job.published
@job.publish!
flash[:notice] = "Twoja oferta jest już widoczna!"
end
redirect_to @job
end
# DELETE /jobs/1
# DELETE /jobs/1.xml
def destroy
@job = Job.find_by_permalink_and_token!(params[:id], params[:token])
@job.destroy
flash[:notice] = "Oferta zostaÅa usuniÄta"
respond_to do |format|
format.html { redirect_to(jobs_url) }
format.xml { head :ok }
end
end
end
diff --git a/app/views/jobs/show.html.erb b/app/views/jobs/show.html.erb
index b3556aa..d3b61eb 100644
--- a/app/views/jobs/show.html.erb
+++ b/app/views/jobs/show.html.erb
@@ -1,84 +1,84 @@
-<% title [@job.category.name, @job.localization.name, @job.company_name, @job.title] %>
+
<div class="box">
<div>
<div class="title">
<h2>
<%= @job.title %>
</h2>
</div>
<dl>
<dt>Typ</dt>
<dd><%= job_label(@job) %></dd>
<dt>Kategoria</dt>
<dd><%= link_to @job.category.name, job_category_path(@job.category) %></dd>
<dt>Ocena</dt>
<dd><%= format_rank(@job.rank) %></dd>
<dt>Pracodawca</dt>
<dd><%= link_to @job.company_name, @job.website, :target => "_blank" %></dd>
<dt>Lokalizacja</dt>
<dd><%= link_to @job.localization.name, localization_path(@job.localization) %></dd>
<% unless @job.framework.nil? %>
<dt>Framework</dt>
<dd><%= link_to @job.framework.name, framework_path(@job.framework) %></dd>
<% end %>
<% if @job.pay_band? %>
<dt>WideÅko zarobkowe</dt>
<dd>
<%= "od #{number_to_currency(@job.price_from)}" unless @job.price_from.nil? %>
<%= "do #{number_to_currency(@job.price_to)}" unless @job.price_to.nil? %> na miesiÄ
c, netto
</dd>
<% end %>
<% unless @job.apply_online %>
<dt>Kontakt</dt>
<dd><%= link_to "Formularz kontaktowy", contact_path(:job_id => @job.id) %></dd>
<% end %>
<% unless (@job.regon.nil? || @job.regon.empty?) %>
<dt>REGON</dt>
<dd><%= @job.regon %> </dd>
<% end %>
<% unless (@job.nip.nil? || @job.nip.empty?) %>
<dt>NIP</dt>
<dd><%= @job.nip %> </dd>
<% end %>
<% unless (@job.krs.nil? || @job.krs.empty?) %>
<dt>KRS</dt>
<dd><%= link_to @job.krs, "http://krs.ms.gov.pl/Podmiot.aspx?nrkrs=#{@job.krs}", :target => "_blank" %> </dd>
<% end %>
<dt>Data rozpoczÄcia</dt>
<dd>
<%= l @job.created_at, :format => :long %>
<br />
<abbr title="<%= @job.created_at.xmlschema %>"><%= distance_of_time_in_words_to_now @job.created_at %> temu</abbr>
</dd>
<dt>Data zakoÅczenia</dt>
<dd>
<%= l @job.end_at, :format => :long %>
<br />
za <abbr title="<%= @job.end_at.xmlschema %>"><%= distance_of_time_in_words_to_now(@job.end_at) %></abbr>
</dd>
<dt>WyÅwietlona</dt>
<dd><%= @job.visits_count %> razy</dd>
</dl>
<div class="clear"></div>
</div>
<div>
<div class="title mini">
<h3>Opis oferty</h3>
</div>
<div class="text">
<%= RedCloth.new(highlight(@job.description, @tags, :highlighter => '<i>\1</i>')).to_html %>
</div>
<p>
<% if permitted_to? :edit, @job %>
<%= link_to 'Edytuj', edit_job_path(@job) %> |
<%= link_to 'Wstecz', jobs_path %>
<% end %>
</p>
</div>
<%= link_to 'Aplikuj online!', new_job_applicant_path(@job), :class => "more" if @job.apply_online %>
</div>
|
macbury/webpraca
|
fdbeb728e9503675e7288b329a7538ba73b88ecc
|
Microfeed
|
diff --git a/config/micro_feed.yml.example.yml b/config/micro_feed.yml.example.yml
new file mode 100644
index 0000000..2c1452f
--- /dev/null
+++ b/config/micro_feed.yml.example.yml
@@ -0,0 +1,18 @@
+blip:
+ login: username
+ password: secret
+
+flaker:
+ login: username
+ password: secret
+
+pinger:
+ login: username
+ password: secret
+
+twitter:
+ login: username
+ password: secret
+
+spinacz:
+ hash: 139c82e0679b64132f528fa71a9ee8d1
\ No newline at end of file
|
macbury/webpraca
|
00be45612402a98a98cdc0d7a359a02224cdc6f1
|
Added info on testing in README
|
diff --git a/README b/README
index 386b035..e6235bd 100644
--- a/README
+++ b/README
@@ -1,6 +1,20 @@
= Instalacja
1. rake db:create
2. rake db:migrate
3. rake db:seed
4. rake webpraca:admin:create
+
+= Running test suite
+
+== Specs
+
+ rake gems:install RAILS_ENV=test
+ rake spec
+
+== Cucumber with capybara
+
+ rake gems:install RAILS_ENV=cucumber
+ rake db:test:prepare # only needed if test database does not exist
+ cucumber features/
+
|
macbury/webpraca
|
4cc678aa26d03045748fa4c37b2630dbff361e0c
|
Added a few working specs with needed config
|
diff --git a/app/models/job.rb b/app/models/job.rb
index 18573db..fead3e9 100644
--- a/app/models/job.rb
+++ b/app/models/job.rb
@@ -1,176 +1,177 @@
JOB_TYPES = ["zlecenie (konkretna usÅuga do wykonania)", "poszukiwanie wspóÅpracowników / oferta pracy", "wolontariat (praca za reklamy, bannery, itp. lub praca za darmo)", "staż/praktyka"]
JOB_LABELS = ["zlecenie", "etat", "wolontariat", "praktyka"]
JOB_ETAT = 1;
JOB_RANK_VALUES = {
:default => 0.3,
:price => 0.8,
:krs => 0.6,
:nip => 0.5,
:regon => 0.6,
:framework_id => 0.7,
:website => 0.3,
:apply_online => 0.2
}
class Job < ActiveRecord::Base
include ActionController::UrlWriter
xss_terminate
has_permalink :title
named_scope :active, :conditions => ["((jobs.end_at >= ?) AND (jobs.published = ?))", Date.current, true]
named_scope :old, :conditions => ["jobs.end_at < ?", Date.current]
named_scope :has_text, lambda { |text| { :conditions => ["((jobs.title ILIKE ?) OR (jobs.description ILIKE ?))", "%#{text}%", "%#{text}%"] } }
validates_presence_of :title, :description, :email, :company_name, :localization_id, :category_id
validates_length_of :title, :within => 3..255
validates_length_of :description, :within => 10..5000
validates_inclusion_of :type_id, :in => 0..JOB_TYPES.size-1
validates_inclusion_of :dlugosc_trwania, :in => 1..60
validates_numericality_of :price_from,
:greater_than => 0,
:unless => Proc.new { |j| j.price_from.nil? }
validates_numericality_of :price_to,
:greater_than => 0,
:unless => Proc.new { |j| j.price_to.nil? }
validates_format_of :email, :with => /([a-z0-9_.-]+)@([a-z0-9-]+)\.([a-z.]+)/i
validates_format_of :website, :with => /(^$)|(^(http|https):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(([0-9]{1,5})?\/.*)?$)/ix
validates_format_of :regon,
:with => /(^$)|(^[0-9]{7,14}$)/
validates_format_of :nip,
:with => /(^$)|(^\d{2,3}-\d{2,3}-\d{2,3}-\d{2,3}$)/
validates_format_of :krs,
:with => /(^$)|(^\d{10})$/
belongs_to :framework
belongs_to :localization
belongs_to :category
has_many :applicants, :dependent => :delete_all
has_many :visits, :dependent => :delete_all
attr_protected :rank, :permalink, :end_at, :token, :published
attr_accessor :framework_name, :localization_name
before_create :create_from_name, :generate_token
before_save :calculate_rank
after_create :send_notification
def self.find_grouped_by_type
return Job.active.count(:type_id, :group => "type_id")
end
def send_notification
JobMailer.deliver_job_posted(self)
end
def generate_token
alphanumerics = ('a'..'z').to_a.concat(('A'..'Z').to_a.concat(('0'..'9').to_a))
salt = alphanumerics.sort_by{rand}.to_s[0..1024]
self.token = Digest::SHA1.hexdigest("--#{salt}--#{self.id}--#{Date.current}--")
generate_token unless Job.find_by_token(self.token).nil?
end
def calculate_rank
self.rank = 1.0
self.rank += visits_count * 0.01 unless visits_count.nil?
[:regon, :nip, :krs, :framework_id, :website, :apply_online].each do |attribute|
val = send(attribute)
inc = JOB_RANK_VALUES[attribute] || JOB_RANK_VALUES[:default]
self.rank += inc unless (val.nil? || (val.class == String && val.empty?) || (val.class == TrueClass))
end
if widelki_zarobkowe?
self.rank += JOB_RANK_VALUES[:price]
price = price_from || price_to
if price >= 10_000 # ciekawe czy ktoÅ da tyle :P
self.rank += 0.8
elsif price >= 7000
self.rank += 0.7
elsif price >= 5000
self.rank += 0.6
elsif price >= 3000
self.rank += 0.3
elsif price < 2000
if self.type_id == JOB_ETAT
self.rank -= 0.6 # bo nikt za grosze nie chce pracowaÄ
else
self.rank += 0.3 # chyba że to biedny student
end
end
end
end
def widelki_zarobkowe?
((!self.price_from.nil? && self.price_from > 0) || (!self.price_to.nil? && self.price_to > 0))
end
def create_from_name
unless (self.framework_name.nil? || self.framework_name.blank?)
framework = Framework.name_like(self.framework_name).first
framework = Framework.create(:name => self.framework_name) if framework.nil?
self.framework = framework
end
unless (self.localization_name.nil? || self.localization_name.blank?)
localization = Localization.name_like(self.localization_name).first
localization = Localization.create(:name => self.localization_name) if localization.nil?
self.localization = localization
end
end
def dlugosc_trwania
date = created_at.nil? ? Date.current.to_date : created_at.to_date
return (read_attribute(:end_at) - date).to_i rescue 14
end
def dlugosc_trwania=(val)
date = created_at.nil? ? Date.current.to_date : created_at.to_date
write_attribute(:end_at, date+val.to_i.days)
end
-
+
+ # TODO: highlited - it's a typo, should be highlighted, I would change it as soon as possible
def highlited?
self.rank >= 4.75
end
def publish!
self.published = true
save
spawn do
tags = [localization.name, category.name, "praca", JOB_LABELS[self.type_id]]
tags << framework.name unless framework.nil?
MicroFeed.send :streams => :all,
:msg => "[#{company_name}] - #{title}",
:tags => tags,
:link => seo_job_url(self, :host => "webpraca.net")
end
end
def visited_by(ip)
visit = visits.find_or_create_by_ip(IPAddr.new(ip).to_i)
visits_count += 1 if visit.new_record?
save
end
def to_param
permalink
end
end
diff --git a/config/environments/test.rb b/config/environments/test.rb
index d6f80a4..debad55 100644
--- a/config/environments/test.rb
+++ b/config/environments/test.rb
@@ -1,28 +1,33 @@
# Settings specified here will take precedence over those in config/environment.rb
# The test environment is used exclusively to run your application's
# test suite. You never need to work with it otherwise. Remember that
# your test database is "scratch space" for the test suite and is wiped
# and recreated between test runs. Don't rely on the data there!
config.cache_classes = true
# Log error messages when you accidentally call methods on nil.
config.whiny_nils = true
# Show full error reports and disable caching
config.action_controller.consider_all_requests_local = true
config.action_controller.perform_caching = false
config.action_view.cache_template_loading = true
# Disable request forgery protection in test environment
config.action_controller.allow_forgery_protection = false
# Tell Action Mailer not to deliver emails to the real world.
# The :test delivery method accumulates sent emails in the
# ActionMailer::Base.deliveries array.
config.action_mailer.delivery_method = :test
# Use SQL instead of Active Record's schema dumper when creating the test database.
# This is necessary if your schema can't be completely dumped by the schema dumper,
# like if you have constraints or database-specific column types
-# config.active_record.schema_format = :sql
\ No newline at end of file
+# config.active_record.schema_format = :sql
+
+config.gem 'rspec', :lib => false, :version => '>=1.2.9' unless File.directory?(File.join(Rails.root, 'vendor/plugins/rspec'))
+config.gem 'rspec-rails', :lib => false, :version => '>=1.2.9' unless File.directory?(File.join(Rails.root, 'vendor/plugins/rspec-rails'))
+config.gem "factory_girl"
+config.gem "faker"
\ No newline at end of file
diff --git a/spec/fixtures/jobs.yml b/spec/fixtures/jobs.yml
new file mode 100644
index 0000000..5bf0293
--- /dev/null
+++ b/spec/fixtures/jobs.yml
@@ -0,0 +1,7 @@
+# Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html
+
+# one:
+# column: value
+#
+# two:
+# column: value
diff --git a/spec/models/job_spec.rb b/spec/models/job_spec.rb
new file mode 100644
index 0000000..ff50324
--- /dev/null
+++ b/spec/models/job_spec.rb
@@ -0,0 +1,20 @@
+require 'spec_helper'
+
+describe Job do
+ before(:each) do
+ end
+
+ it "should create a new instance given valid attributes" do
+ Factory.build(:job).save!
+ end
+
+ describe "highlighted?" do
+ it "should be highlighted if rank >= 4.75" do
+ Factory.build(:job, :rank => 5).should be_highlited
+ end
+
+ it "should not be highlighted if rank < 4.75" do
+ Factory.build(:job, :rank => 4.74).should_not be_highlited
+ end
+ end
+end
diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb
index 0ba1470..5b98019 100644
--- a/spec/spec_helper.rb
+++ b/spec/spec_helper.rb
@@ -1,54 +1,56 @@
# This file is copied to ~/spec when you run 'ruby script/generate rspec'
# from the project root directory.
ENV["RAILS_ENV"] ||= 'test'
require File.expand_path(File.join(File.dirname(__FILE__),'..','config','environment'))
require 'spec/autorun'
require 'spec/rails'
# Uncomment the next line to use webrat's matchers
#require 'webrat/integrations/rspec-rails'
# Requires supporting files with custom matchers and macros, etc,
# in ./support/ and its subdirectories.
Dir[File.expand_path(File.join(File.dirname(__FILE__),'support','**','*.rb'))].each {|f| require f}
+require Rails.root.join("spec/factories")
+
Spec::Runner.configure do |config|
# If you're not using ActiveRecord you should remove these
# lines, delete config/database.yml and disable :active_record
# in your config/boot.rb
config.use_transactional_fixtures = true
config.use_instantiated_fixtures = false
config.fixture_path = RAILS_ROOT + '/spec/fixtures/'
# == Fixtures
#
# You can declare fixtures for each example_group like this:
# describe "...." do
# fixtures :table_a, :table_b
#
# Alternatively, if you prefer to declare them only once, you can
# do so right here. Just uncomment the next line and replace the fixture
# names with your fixtures.
#
# config.global_fixtures = :table_a, :table_b
#
# If you declare global fixtures, be aware that they will be declared
# for all of your examples, even those that don't use them.
#
# You can also declare which fixtures to use (for example fixtures for test/fixtures):
#
# config.fixture_path = RAILS_ROOT + '/spec/fixtures/'
#
# == Mock Framework
#
# RSpec uses it's own mocking framework by default. If you prefer to
# use mocha, flexmock or RR, uncomment the appropriate line:
#
# config.mock_with :mocha
# config.mock_with :flexmock
# config.mock_with :rr
#
# == Notes
#
# For more information take a look at Spec::Runner::Configuration and Spec::Runner
end
|
macbury/webpraca
|
fa467f950b552fb74a75a292933f191d48745aa6
|
Generated rspec
|
diff --git a/lib/tasks/rspec.rake b/lib/tasks/rspec.rake
new file mode 100644
index 0000000..dba3ffc
--- /dev/null
+++ b/lib/tasks/rspec.rake
@@ -0,0 +1,144 @@
+gem 'test-unit', '1.2.3' if RUBY_VERSION.to_f >= 1.9
+rspec_gem_dir = nil
+Dir["#{RAILS_ROOT}/vendor/gems/*"].each do |subdir|
+ rspec_gem_dir = subdir if subdir.gsub("#{RAILS_ROOT}/vendor/gems/","") =~ /^(\w+-)?rspec-(\d+)/ && File.exist?("#{subdir}/lib/spec/rake/spectask.rb")
+end
+rspec_plugin_dir = File.expand_path(File.dirname(__FILE__) + '/../../vendor/plugins/rspec')
+
+if rspec_gem_dir && (test ?d, rspec_plugin_dir)
+ raise "\n#{'*'*50}\nYou have rspec installed in both vendor/gems and vendor/plugins\nPlease pick one and dispose of the other.\n#{'*'*50}\n\n"
+end
+
+if rspec_gem_dir
+ $LOAD_PATH.unshift("#{rspec_gem_dir}/lib")
+elsif File.exist?(rspec_plugin_dir)
+ $LOAD_PATH.unshift("#{rspec_plugin_dir}/lib")
+end
+
+# Don't load rspec if running "rake gems:*"
+unless ARGV.any? {|a| a =~ /^gems/}
+
+begin
+ require 'spec/rake/spectask'
+rescue MissingSourceFile
+ module Spec
+ module Rake
+ class SpecTask
+ def initialize(name)
+ task name do
+ # if rspec-rails is a configured gem, this will output helpful material and exit ...
+ require File.expand_path(File.join(File.dirname(__FILE__),"..","..","config","environment"))
+
+ # ... otherwise, do this:
+ raise <<-MSG
+
+#{"*" * 80}
+* You are trying to run an rspec rake task defined in
+* #{__FILE__},
+* but rspec can not be found in vendor/gems, vendor/plugins or system gems.
+#{"*" * 80}
+MSG
+ end
+ end
+ end
+ end
+ end
+end
+
+Rake.application.instance_variable_get('@tasks').delete('default')
+
+spec_prereq = File.exist?(File.join(RAILS_ROOT, 'config', 'database.yml')) ? "db:test:prepare" : :noop
+task :noop do
+end
+
+task :default => :spec
+task :stats => "spec:statsetup"
+
+desc "Run all specs in spec directory (excluding plugin specs)"
+Spec::Rake::SpecTask.new(:spec => spec_prereq) do |t|
+ t.spec_opts = ['--options', "\"#{RAILS_ROOT}/spec/spec.opts\""]
+ t.spec_files = FileList['spec/**/*_spec.rb']
+end
+
+namespace :spec do
+ desc "Run all specs in spec directory with RCov (excluding plugin specs)"
+ Spec::Rake::SpecTask.new(:rcov) do |t|
+ t.spec_opts = ['--options', "\"#{RAILS_ROOT}/spec/spec.opts\""]
+ t.spec_files = FileList['spec/**/*_spec.rb']
+ t.rcov = true
+ t.rcov_opts = lambda do
+ IO.readlines("#{RAILS_ROOT}/spec/rcov.opts").map {|l| l.chomp.split " "}.flatten
+ end
+ end
+
+ desc "Print Specdoc for all specs (excluding plugin specs)"
+ Spec::Rake::SpecTask.new(:doc) do |t|
+ t.spec_opts = ["--format", "specdoc", "--dry-run"]
+ t.spec_files = FileList['spec/**/*_spec.rb']
+ end
+
+ desc "Print Specdoc for all plugin examples"
+ Spec::Rake::SpecTask.new(:plugin_doc) do |t|
+ t.spec_opts = ["--format", "specdoc", "--dry-run"]
+ t.spec_files = FileList['vendor/plugins/**/spec/**/*_spec.rb'].exclude('vendor/plugins/rspec/*')
+ end
+
+ [:models, :controllers, :views, :helpers, :lib, :integration].each do |sub|
+ desc "Run the code examples in spec/#{sub}"
+ Spec::Rake::SpecTask.new(sub => spec_prereq) do |t|
+ t.spec_opts = ['--options', "\"#{RAILS_ROOT}/spec/spec.opts\""]
+ t.spec_files = FileList["spec/#{sub}/**/*_spec.rb"]
+ end
+ end
+
+ desc "Run the code examples in vendor/plugins (except RSpec's own)"
+ Spec::Rake::SpecTask.new(:plugins => spec_prereq) do |t|
+ t.spec_opts = ['--options', "\"#{RAILS_ROOT}/spec/spec.opts\""]
+ t.spec_files = FileList['vendor/plugins/**/spec/**/*_spec.rb'].exclude('vendor/plugins/rspec/*').exclude("vendor/plugins/rspec-rails/*")
+ end
+
+ namespace :plugins do
+ desc "Runs the examples for rspec_on_rails"
+ Spec::Rake::SpecTask.new(:rspec_on_rails) do |t|
+ t.spec_opts = ['--options', "\"#{RAILS_ROOT}/spec/spec.opts\""]
+ t.spec_files = FileList['vendor/plugins/rspec-rails/spec/**/*_spec.rb']
+ end
+ end
+
+ # Setup specs for stats
+ task :statsetup do
+ require 'code_statistics'
+ ::STATS_DIRECTORIES << %w(Model\ specs spec/models) if File.exist?('spec/models')
+ ::STATS_DIRECTORIES << %w(View\ specs spec/views) if File.exist?('spec/views')
+ ::STATS_DIRECTORIES << %w(Controller\ specs spec/controllers) if File.exist?('spec/controllers')
+ ::STATS_DIRECTORIES << %w(Helper\ specs spec/helpers) if File.exist?('spec/helpers')
+ ::STATS_DIRECTORIES << %w(Library\ specs spec/lib) if File.exist?('spec/lib')
+ ::STATS_DIRECTORIES << %w(Routing\ specs spec/routing) if File.exist?('spec/routing')
+ ::STATS_DIRECTORIES << %w(Integration\ specs spec/integration) if File.exist?('spec/integration')
+ ::CodeStatistics::TEST_TYPES << "Model specs" if File.exist?('spec/models')
+ ::CodeStatistics::TEST_TYPES << "View specs" if File.exist?('spec/views')
+ ::CodeStatistics::TEST_TYPES << "Controller specs" if File.exist?('spec/controllers')
+ ::CodeStatistics::TEST_TYPES << "Helper specs" if File.exist?('spec/helpers')
+ ::CodeStatistics::TEST_TYPES << "Library specs" if File.exist?('spec/lib')
+ ::CodeStatistics::TEST_TYPES << "Routing specs" if File.exist?('spec/routing')
+ ::CodeStatistics::TEST_TYPES << "Integration specs" if File.exist?('spec/integration')
+ end
+
+ namespace :db do
+ namespace :fixtures do
+ desc "Load fixtures (from spec/fixtures) into the current environment's database. Load specific fixtures using FIXTURES=x,y. Load from subdirectory in test/fixtures using FIXTURES_DIR=z."
+ task :load => :environment do
+ ActiveRecord::Base.establish_connection(Rails.env)
+ base_dir = File.join(Rails.root, 'spec', 'fixtures')
+ fixtures_dir = ENV['FIXTURES_DIR'] ? File.join(base_dir, ENV['FIXTURES_DIR']) : base_dir
+
+ require 'active_record/fixtures'
+ (ENV['FIXTURES'] ? ENV['FIXTURES'].split(/,/).map {|f| File.join(fixtures_dir, f) } : Dir.glob(File.join(fixtures_dir, '*.{yml,csv}'))).each do |fixture_file|
+ Fixtures.create_fixtures(File.dirname(fixture_file), File.basename(fixture_file, '.*'))
+ end
+ end
+ end
+ end
+end
+
+end
diff --git a/script/autospec b/script/autospec
new file mode 100755
index 0000000..837bbd7
--- /dev/null
+++ b/script/autospec
@@ -0,0 +1,6 @@
+#!/usr/bin/env ruby
+gem 'test-unit', '1.2.3' if RUBY_VERSION.to_f >= 1.9
+ENV['RSPEC'] = 'true' # allows autotest to discover rspec
+ENV['AUTOTEST'] = 'true' # allows autotest to run w/ color on linux
+system((RUBY_PLATFORM =~ /mswin|mingw/ ? 'autotest.bat' : 'autotest'), *ARGV) ||
+ $stderr.puts("Unable to find autotest. Please install ZenTest or fix your PATH")
diff --git a/script/spec b/script/spec
new file mode 100755
index 0000000..46fdbe6
--- /dev/null
+++ b/script/spec
@@ -0,0 +1,10 @@
+#!/usr/bin/env ruby
+if ARGV.any? {|arg| %w[--drb -X --generate-options -G --help -h --version -v].include?(arg)}
+ require 'rubygems' unless ENV['NO_RUBYGEMS']
+else
+ gem 'test-unit', '1.2.3' if RUBY_VERSION.to_f >= 1.9
+ ENV["RAILS_ENV"] ||= 'test'
+ require File.expand_path(File.dirname(__FILE__) + "/../config/environment") unless defined?(RAILS_ROOT)
+end
+require 'spec/autorun'
+exit ::Spec::Runner::CommandLine.run
diff --git a/spec/rcov.opts b/spec/rcov.opts
new file mode 100644
index 0000000..274ed51
--- /dev/null
+++ b/spec/rcov.opts
@@ -0,0 +1,2 @@
+--exclude "spec/*,gems/*"
+--rails
\ No newline at end of file
diff --git a/spec/spec.opts b/spec/spec.opts
new file mode 100644
index 0000000..391705b
--- /dev/null
+++ b/spec/spec.opts
@@ -0,0 +1,4 @@
+--colour
+--format progress
+--loadby mtime
+--reverse
diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb
new file mode 100644
index 0000000..0ba1470
--- /dev/null
+++ b/spec/spec_helper.rb
@@ -0,0 +1,54 @@
+# This file is copied to ~/spec when you run 'ruby script/generate rspec'
+# from the project root directory.
+ENV["RAILS_ENV"] ||= 'test'
+require File.expand_path(File.join(File.dirname(__FILE__),'..','config','environment'))
+require 'spec/autorun'
+require 'spec/rails'
+
+# Uncomment the next line to use webrat's matchers
+#require 'webrat/integrations/rspec-rails'
+
+# Requires supporting files with custom matchers and macros, etc,
+# in ./support/ and its subdirectories.
+Dir[File.expand_path(File.join(File.dirname(__FILE__),'support','**','*.rb'))].each {|f| require f}
+
+Spec::Runner.configure do |config|
+ # If you're not using ActiveRecord you should remove these
+ # lines, delete config/database.yml and disable :active_record
+ # in your config/boot.rb
+ config.use_transactional_fixtures = true
+ config.use_instantiated_fixtures = false
+ config.fixture_path = RAILS_ROOT + '/spec/fixtures/'
+
+ # == Fixtures
+ #
+ # You can declare fixtures for each example_group like this:
+ # describe "...." do
+ # fixtures :table_a, :table_b
+ #
+ # Alternatively, if you prefer to declare them only once, you can
+ # do so right here. Just uncomment the next line and replace the fixture
+ # names with your fixtures.
+ #
+ # config.global_fixtures = :table_a, :table_b
+ #
+ # If you declare global fixtures, be aware that they will be declared
+ # for all of your examples, even those that don't use them.
+ #
+ # You can also declare which fixtures to use (for example fixtures for test/fixtures):
+ #
+ # config.fixture_path = RAILS_ROOT + '/spec/fixtures/'
+ #
+ # == Mock Framework
+ #
+ # RSpec uses it's own mocking framework by default. If you prefer to
+ # use mocha, flexmock or RR, uncomment the appropriate line:
+ #
+ # config.mock_with :mocha
+ # config.mock_with :flexmock
+ # config.mock_with :rr
+ #
+ # == Notes
+ #
+ # For more information take a look at Spec::Runner::Configuration and Spec::Runner
+end
|
macbury/webpraca
|
7d977d2172eafc42e121920d8a8d9161bb1b4f09
|
Browsing categories feature
|
diff --git a/features/categories.feature b/features/categories.feature
new file mode 100644
index 0000000..eddcbdf
--- /dev/null
+++ b/features/categories.feature
@@ -0,0 +1,16 @@
+Feature: Browse jobs in categories
+ In order to find interesting jobs
+ As a user
+ I can browse through job offers in categories
+
+ Scenario: Categories
+ Given a job titled "Google CEO" exists in category "IT"
+ And a job titled "Senior Rails developer" exists in category "Programowanie"
+ And I am on the homepage
+ When I follow "IT" within ".categories"
+ And I should see "Google CEO"
+ And I should not see "Senior Rails Developer"
+ When I follow "Programowanie" within ".categories"
+ And I should see "Senior Rails Developer"
+ And I should not see "Google CEO"
+
diff --git a/features/step_definitions/job_steps.rb b/features/step_definitions/job_steps.rb
new file mode 100644
index 0000000..483e535
--- /dev/null
+++ b/features/step_definitions/job_steps.rb
@@ -0,0 +1,4 @@
+Given /^a job titled "([^\"]*)" exists in category "([^\"]*)"$/ do |title, category_name|
+ category = Category.find_by_name(category_name) || Factory.create(:category, :name => category_name)
+ Factory.create(:job, :title => title, :category => category)
+end
|
macbury/webpraca
|
66973558eebd257fd099c9538714218084d81049
|
Do not require smtp settings for test environments (it should moved to environments/*.rb files imho)
|
diff --git a/app/models/job_mailer.rb b/app/models/job_mailer.rb
index 5dcc25b..af05229 100644
--- a/app/models/job_mailer.rb
+++ b/app/models/job_mailer.rb
@@ -1,37 +1,39 @@
class JobMailer < ActionMailer::Base
include ActionController::UrlWriter
def job_applicant(applicant)
setup_email(applicant.job.email)
if applicant.job.email_title.nil? || applicant.job.email_title.empty?
@subject = "webpraca.net - PojawiÅa siÄ osoba zainteresowana ofertÄ
'#{applicant.job.title}'"
else
@subject = applicant.job.email_title
end
@body[:job] = applicant.job
@body[:applicant] = applicant
@body[:job_path] = seo_job_url(applicant.job)
@body[:attachment_path] = download_job_applicant_url(applicant.job, applicant.token) if applicant.have_attachment?
end
def job_posted(job)
setup_email(job.email)
@subject = "webpraca.net - Twoja oferta zostaÅa dodana"
@body[:job] = job
@body[:job_path] = seo_job_url(job)
@body[:publish_path] = publish_job_url(job, :token => job.token)
@body[:edit_path] = edit_job_url(job, :token => job.token)
@body[:destroy_path] = destroy_job_url(job, :token => job.token)
end
protected
def setup_email(email)
@recipients = email
#@subject = "[mycode] "
@sent_on = Time.now
- @from = ActionMailer::Base.smtp_settings[:from]
+ if ActionMailer::Base.smtp_settings
+ @from = ActionMailer::Base.smtp_settings[:from]
+ end
default_url_options[:host] = "webpraca.net"
end
end
diff --git a/config/initializers/mailer.rb b/config/initializers/mailer.rb
index 6c3a603..e9739a5 100644
--- a/config/initializers/mailer.rb
+++ b/config/initializers/mailer.rb
@@ -1,14 +1,16 @@
-require "smtp_tls"
-ActionMailer::Base.delivery_method = :smtp
-ActionMailer::Base.default_charset = 'utf-8'
-ActionMailer::Base.perform_deliveries = true
-ActionMailer::Base.raise_delivery_errors = true
+if RAILS_ENV != "test" and RAILS_ENV != "cucumber"
+ require "smtp_tls"
+ ActionMailer::Base.delivery_method = :smtp
+ ActionMailer::Base.default_charset = 'utf-8'
+ ActionMailer::Base.perform_deliveries = true
+ ActionMailer::Base.raise_delivery_errors = true
-begin
- ActionMailer::Base.smtp_settings = YAML.load_file("#{RAILS_ROOT}/config/mailer.yml")[Rails.env]
-rescue Errno::ENOENT
- raise "Could not find config/website_config.yml, example is in config/website_config.yml.example"
-end
+ begin
+ ActionMailer::Base.smtp_settings = YAML.load_file("#{RAILS_ROOT}/config/mailer.yml")[Rails.env]
+ rescue Errno::ENOENT
+ raise "Could not find config/website_config.yml, example is in config/website_config.yml.example"
+ end
-ActionMailer::Base.smtp_settings[:tsl] = true
-ActionMailer::Base.smtp_settings[:authentication] = :login
\ No newline at end of file
+ ActionMailer::Base.smtp_settings[:tsl] = true
+ ActionMailer::Base.smtp_settings[:authentication] = :login
+end
\ No newline at end of file
|
macbury/webpraca
|
b1860befeb2347614ebb826535d9d8be4c888463
|
Added factories in spec/factories.rb
|
diff --git a/features/support/env.rb b/features/support/env.rb
index fbfc10e..9d193c3 100644
--- a/features/support/env.rb
+++ b/features/support/env.rb
@@ -1,55 +1,57 @@
# IMPORTANT: This file is generated by cucumber-rails - edit at your own peril.
# It is recommended to regenerate this file in the future when you upgrade to a
# newer version of cucumber-rails. Consider adding your own code to a new file
# instead of editing this one. Cucumber will automatically load all features/**/*.rb
# files.
ENV["RAILS_ENV"] ||= "cucumber"
require File.expand_path(File.dirname(__FILE__) + '/../../config/environment')
require 'cucumber/formatter/unicode' # Remove this line if you don't want Cucumber Unicode support
require 'cucumber/rails/rspec'
require 'cucumber/rails/world'
require 'cucumber/rails/active_record'
require 'cucumber/web/tableish'
require 'capybara/rails'
require 'capybara/cucumber'
require 'capybara/session'
require 'cucumber/rails/capybara_javascript_emulation' # Lets you click links with onclick javascript handlers without using @culerity or @javascript
# Capybara defaults to XPath selectors rather than Webrat's default of CSS3. In
# order to ease the transition to Capybara we set the default here. If you'd
# prefer to use XPath just remove this line and adjust any selectors in your
# steps to use the XPath syntax.
Capybara.default_selector = :css
# If you set this to false, any error raised from within your app will bubble
# up to your step definition and out to cucumber unless you catch it somewhere
# on the way. You can make Rails rescue errors and render error pages on a
# per-scenario basis by tagging a scenario or feature with the @allow-rescue tag.
#
# If you set this to true, Rails will rescue all errors and render error
# pages, more or less in the same way your application would behave in the
# default production environment. It's not recommended to do this for all
# of your scenarios, as this makes it hard to discover errors in your application.
ActionController::Base.allow_rescue = false
# If you set this to true, each scenario will run in a database transaction.
# You can still turn off transactions on a per-scenario basis, simply tagging
# a feature or scenario with the @no-txn tag. If you are using Capybara,
# tagging with @culerity or @javascript will also turn transactions off.
#
# If you set this to false, transactions will be off for all scenarios,
# regardless of whether you use @no-txn or not.
#
# Beware that turning transactions off will leave data in your database
# after each scenario, which can lead to hard-to-debug failures in
# subsequent scenarios. If you do this, we recommend you create a Before
# block that will explicitly put your database in a known state.
Cucumber::Rails::World.use_transactional_fixtures = true
# How to clean your database when transactions are turned off. See
# http://github.com/bmabey/database_cleaner for more info.
require 'database_cleaner'
DatabaseCleaner.strategy = :truncation
+require 'factory_girl/step_definitions'
+
diff --git a/spec/factories.rb b/spec/factories.rb
new file mode 100644
index 0000000..735b6bc
--- /dev/null
+++ b/spec/factories.rb
@@ -0,0 +1,21 @@
+Factory.define :job do |f|
+ f.title { "Google CEO" }
+ # it's faster to fing existing record, than create new one
+ f.category { |c| Category.find(:first) || c.association(:category) }
+ f.localization { |l| Localization.find(:first) || l.association(:localization) }
+ f.type_id 0
+ f.description "You'll probably like this job."
+ f.company_name "Google"
+ f.email "google@google.com"
+ f.published true
+ f.end_at { DateTime.now + 1.month }
+end
+
+Factory.define :category do |f|
+ f.sequence(:name) {|n| "category #{n}" }
+end
+
+Factory.define :localization do |f|
+ f.name "Warszawa"
+ f.permalink "warszawa"
+end
\ No newline at end of file
|
macbury/webpraca
|
74535f1af964268991cb1d41dbfd45ae6231e1da
|
Generated cucumber config with capybara
|
diff --git a/config/cucumber.yml b/config/cucumber.yml
new file mode 100644
index 0000000..55ed193
--- /dev/null
+++ b/config/cucumber.yml
@@ -0,0 +1,10 @@
+<%
+rerun = File.file?('rerun.txt') ? IO.read('rerun.txt') : ""
+#rerun_opts = rerun.to_s.strip.empty? ? "--format progress features" : "--format #{ENV['CUCUMBER_FORMAT'] || 'pretty'} #{rerun}"
+#std_opts = "#{rerun_opts} --format rerun --out rerun.txt --strict --tags ~@wip"
+# options above are from generated cucumber config, I don't like the whole idea of rerun feature, so I will
+# just stick to plain old options
+std_opts = "--format pretty --strict --tags ~@wip"
+%>
+default: <%= std_opts %>
+wip: --tags @wip:3 --wip features
diff --git a/config/environments/cucumber.rb b/config/environments/cucumber.rb
new file mode 100644
index 0000000..312889e
--- /dev/null
+++ b/config/environments/cucumber.rb
@@ -0,0 +1,30 @@
+# Edit at your own peril - it's recommended to regenerate this file
+# in the future when you upgrade to a newer version of Cucumber.
+
+# IMPORTANT: Setting config.cache_classes to false is known to
+# break Cucumber's use_transactional_fixtures method.
+# For more information see https://rspec.lighthouseapp.com/projects/16211/tickets/165
+config.cache_classes = true
+
+# Log error messages when you accidentally call methods on nil.
+config.whiny_nils = true
+
+# Show full error reports and disable caching
+config.action_controller.consider_all_requests_local = true
+config.action_controller.perform_caching = false
+
+# Disable request forgery protection in test environment
+config.action_controller.allow_forgery_protection = false
+
+# Tell Action Mailer not to deliver emails to the real world.
+# The :test delivery method accumulates sent emails in the
+# ActionMailer::Base.deliveries array.
+config.action_mailer.delivery_method = :test
+
+config.gem 'cucumber-rails', :lib => false, :version => '>=0.2.3' unless File.directory?(File.join(Rails.root, 'vendor/plugins/cucumber-rails'))
+config.gem 'database_cleaner', :lib => false, :version => '>=0.2.3' unless File.directory?(File.join(Rails.root, 'vendor/plugins/database_cleaner'))
+config.gem 'capybara', :lib => false, :version => '>=0.2.0' unless File.directory?(File.join(Rails.root, 'vendor/plugins/capybara'))
+config.gem 'rspec', :lib => false, :version => '>=1.2.9' unless File.directory?(File.join(Rails.root, 'vendor/plugins/rspec'))
+config.gem 'rspec-rails', :lib => false, :version => '>=1.2.9' unless File.directory?(File.join(Rails.root, 'vendor/plugins/rspec-rails'))
+config.gem "factory_girl"
+config.gem "faker"
\ No newline at end of file
diff --git a/features/step_definitions/web_steps.rb b/features/step_definitions/web_steps.rb
new file mode 100644
index 0000000..995b201
--- /dev/null
+++ b/features/step_definitions/web_steps.rb
@@ -0,0 +1,192 @@
+# IMPORTANT: This file is generated by cucumber-rails - edit at your own peril.
+# It is recommended to regenerate this file in the future when you upgrade to a
+# newer version of cucumber-rails. Consider adding your own code to a new file
+# instead of editing this one. Cucumber will automatically load all features/**/*.rb
+# files.
+
+
+require 'uri'
+require File.expand_path(File.join(File.dirname(__FILE__), "..", "support", "paths"))
+
+module WithinHelpers
+ def with_scope(locator)
+ within(locator || 'html') { yield }
+ end
+end
+World(WithinHelpers)
+
+Given /^(?:|I )am on (.+)$/ do |page_name|
+ visit path_to(page_name)
+end
+
+When /^(?:|I )go to (.+)$/ do |page_name|
+ visit path_to(page_name)
+end
+
+When /^(?:|I )press "([^\"]*)"(?: within "([^\"]*)")?$/ do |button, selector|
+ with_scope(selector) do
+ click_button(button)
+ end
+end
+
+When /^(?:|I )follow "([^\"]*)"(?: within "([^\"]*)")?$/ do |link, selector|
+ with_scope(selector) do
+ click_link(link)
+ end
+end
+
+When /^(?:|I )fill in "([^\"]*)" with "([^\"]*)"(?: within "([^\"]*)")?$/ do |field, value, selector|
+ with_scope(selector) do
+ fill_in(field, :with => value)
+ end
+end
+
+When /^(?:|I )fill in "([^\"]*)" for "([^\"]*)"(?: within "([^\"]*)")?$/ do |value, field, selector|
+ with_scope(selector) do
+ fill_in(field, :with => value)
+ end
+end
+
+# Use this to fill in an entire form with data from a table. Example:
+#
+# When I fill in the following:
+# | Account Number | 5002 |
+# | Expiry date | 2009-11-01 |
+# | Note | Nice guy |
+# | Wants Email? | |
+#
+# TODO: Add support for checkbox, select og option
+# based on naming conventions.
+#
+When /^(?:|I )fill in the following(?: within "([^\"]*)"|)?:$/ do |fields, selector|
+ with_scope(selector) do
+ fields.rows_hash.each do |name, value|
+ When %{I fill in "#{name}" with "#{value}"}
+ end
+ end
+end
+
+When /^(?:|I )select "([^\"]*)" from "([^\"]*)"(?: within "([^\"]*)")?$/ do |value, field, selector|
+ with_scope(selector) do
+ select(value, :from => field)
+ end
+end
+
+When /^(?:|I )check "([^\"]*)"(?: within "([^\"]*)")?$/ do |field, selector|
+ with_scope(selector) do
+ check(field)
+ end
+end
+
+When /^(?:|I )uncheck "([^\"]*)"(?: within "([^\"]*)")?$/ do |field, selector|
+ with_scope(selector) do
+ uncheck(field)
+ end
+end
+
+When /^(?:|I )choose "([^\"]*)"(?: within "([^\"]*)")?$/ do |field, selector|
+ with_scope(selector) do
+ choose(field)
+ end
+end
+
+When /^(?:|I )attach the file "([^\"]*)" to "([^\"]*)"(?: within "([^\"]*)")?$/ do |path, field, selector|
+ with_scope(selector) do
+ attach_file(field, path)
+ end
+end
+
+Then /^(?:|I )should see "([^\"]*)"(?: within "([^\"]*)")?$/ do |text, selector|
+ with_scope(selector) do
+ if defined?(Spec::Rails::Matchers)
+ page.should have_content(text)
+ else
+ assert page.has_content?(text)
+ end
+ end
+end
+
+Then /^(?:|I )should see \/([^\/]*)\/(?: within "([^\"]*)")?$/ do |regexp, selector|
+ regexp = Regexp.new(regexp)
+ with_scope(selector) do
+ if defined?(Spec::Rails::Matchers)
+ page.should have_xpath('//*', :text => regexp)
+ else
+ assert page.has_xpath?('//*', :text => regexp)
+ end
+ end
+end
+
+Then /^(?:|I )should not see "([^\"]*)"(?: within "([^\"]*)")?$/ do |text, selector|
+ with_scope(selector) do
+ if defined?(Spec::Rails::Matchers)
+ page.should_not have_content(text)
+ else
+ assert_not page.has_content?(text)
+ end
+ end
+end
+
+Then /^(?:|I )should not see \/([^\/]*)\/(?: within "([^\"]*)")?$/ do |regexp, selector|
+ regexp = Regexp.new(regexp)
+ with_scope(selector) do
+ if defined?(Spec::Rails::Matchers)
+ page.should_not have_xpath('//*', :text => regexp)
+ else
+ assert_not page.has_xpath?('//*', :text => regexp)
+ end
+ end
+end
+
+Then /^the "([^\"]*)" field(?: within "([^\"]*)")? should contain "([^\"]*)"$/ do |field, selector, value|
+ with_scope(selector) do
+ if defined?(Spec::Rails::Matchers)
+ find_field(field).value.should =~ /#{value}/
+ else
+ assert_match(/#{value}/, field_labeled(field).value)
+ end
+ end
+end
+
+Then /^the "([^\"]*)" field(?: within "([^\"]*)")? should not contain "([^\"]*)"$/ do |field, selector, value|
+ with_scope(selector) do
+ if defined?(Spec::Rails::Matchers)
+ find_field(field).value.should_not =~ /#{value}/
+ else
+ assert_no_match(/#{value}/, find_field(field).value)
+ end
+ end
+end
+
+Then /^the "([^\"]*)" checkbox(?: within "([^\"]*)")? should be checked$/ do |label, selector|
+ with_scope(selector) do
+ if defined?(Spec::Rails::Matchers)
+ find_field(label)['checked'].should == 'checked'
+ else
+ assert field_labeled(label)['checked'] == 'checked'
+ end
+ end
+end
+
+Then /^the "([^\"]*)" checkbox(?: within "([^\"]*)")? should not be checked$/ do |label, selector|
+ with_scope(selector) do
+ if defined?(Spec::Rails::Matchers)
+ find_field(label)['checked'].should_not == 'checked'
+ else
+ assert field_labeled(label)['checked'] != 'checked'
+ end
+ end
+end
+
+Then /^(?:|I )should be on (.+)$/ do |page_name|
+ current_path = URI.parse(current_url).select(:path, :query).compact.join('?')
+ if defined?(Spec::Rails::Matchers)
+ current_path.should == path_to(page_name)
+ else
+ assert_equal path_to(page_name), current_path
+ end
+end
+
+Then /^show me the page$/ do
+ save_and_open_page
+end
\ No newline at end of file
diff --git a/features/support/env.rb b/features/support/env.rb
new file mode 100644
index 0000000..fbfc10e
--- /dev/null
+++ b/features/support/env.rb
@@ -0,0 +1,55 @@
+# IMPORTANT: This file is generated by cucumber-rails - edit at your own peril.
+# It is recommended to regenerate this file in the future when you upgrade to a
+# newer version of cucumber-rails. Consider adding your own code to a new file
+# instead of editing this one. Cucumber will automatically load all features/**/*.rb
+# files.
+
+ENV["RAILS_ENV"] ||= "cucumber"
+require File.expand_path(File.dirname(__FILE__) + '/../../config/environment')
+
+require 'cucumber/formatter/unicode' # Remove this line if you don't want Cucumber Unicode support
+require 'cucumber/rails/rspec'
+require 'cucumber/rails/world'
+require 'cucumber/rails/active_record'
+require 'cucumber/web/tableish'
+
+require 'capybara/rails'
+require 'capybara/cucumber'
+require 'capybara/session'
+require 'cucumber/rails/capybara_javascript_emulation' # Lets you click links with onclick javascript handlers without using @culerity or @javascript
+# Capybara defaults to XPath selectors rather than Webrat's default of CSS3. In
+# order to ease the transition to Capybara we set the default here. If you'd
+# prefer to use XPath just remove this line and adjust any selectors in your
+# steps to use the XPath syntax.
+Capybara.default_selector = :css
+
+# If you set this to false, any error raised from within your app will bubble
+# up to your step definition and out to cucumber unless you catch it somewhere
+# on the way. You can make Rails rescue errors and render error pages on a
+# per-scenario basis by tagging a scenario or feature with the @allow-rescue tag.
+#
+# If you set this to true, Rails will rescue all errors and render error
+# pages, more or less in the same way your application would behave in the
+# default production environment. It's not recommended to do this for all
+# of your scenarios, as this makes it hard to discover errors in your application.
+ActionController::Base.allow_rescue = false
+
+# If you set this to true, each scenario will run in a database transaction.
+# You can still turn off transactions on a per-scenario basis, simply tagging
+# a feature or scenario with the @no-txn tag. If you are using Capybara,
+# tagging with @culerity or @javascript will also turn transactions off.
+#
+# If you set this to false, transactions will be off for all scenarios,
+# regardless of whether you use @no-txn or not.
+#
+# Beware that turning transactions off will leave data in your database
+# after each scenario, which can lead to hard-to-debug failures in
+# subsequent scenarios. If you do this, we recommend you create a Before
+# block that will explicitly put your database in a known state.
+Cucumber::Rails::World.use_transactional_fixtures = true
+
+# How to clean your database when transactions are turned off. See
+# http://github.com/bmabey/database_cleaner for more info.
+require 'database_cleaner'
+DatabaseCleaner.strategy = :truncation
+
diff --git a/features/support/paths.rb b/features/support/paths.rb
new file mode 100644
index 0000000..c575c07
--- /dev/null
+++ b/features/support/paths.rb
@@ -0,0 +1,27 @@
+module NavigationHelpers
+ # Maps a name to a path. Used by the
+ #
+ # When /^I go to (.+)$/ do |page_name|
+ #
+ # step definition in web_steps.rb
+ #
+ def path_to(page_name)
+ case page_name
+
+ when /the home\s?page/
+ '/'
+
+ # Add more mappings here.
+ # Here is an example that pulls values out of the Regexp:
+ #
+ # when /^(.*)'s profile page$/i
+ # user_profile_path(User.find_by_login($1))
+
+ else
+ raise "Can't find mapping from \"#{page_name}\" to a path.\n" +
+ "Now, go and add a mapping in #{__FILE__}"
+ end
+ end
+end
+
+World(NavigationHelpers)
diff --git a/lib/tasks/cucumber.rake b/lib/tasks/cucumber.rake
new file mode 100644
index 0000000..ab04dc8
--- /dev/null
+++ b/lib/tasks/cucumber.rake
@@ -0,0 +1,47 @@
+# IMPORTANT: This file is generated by cucumber-rails - edit at your own peril.
+# It is recommended to regenerate this file in the future when you upgrade to a
+# newer version of cucumber-rails. Consider adding your own code to a new file
+# instead of editing this one. Cucumber will automatically load all features/**/*.rb
+# files.
+
+
+unless ARGV.any? {|a| a =~ /^gems/} # Don't load anything when running the gems:* tasks
+
+vendored_cucumber_bin = Dir["#{RAILS_ROOT}/vendor/{gems,plugins}/cucumber*/bin/cucumber"].first
+$LOAD_PATH.unshift(File.dirname(vendored_cucumber_bin) + '/../lib') unless vendored_cucumber_bin.nil?
+
+begin
+ require 'cucumber/rake/task'
+
+ namespace :cucumber do
+ Cucumber::Rake::Task.new({:ok => 'db:test:prepare'}, 'Run features that should pass') do |t|
+ t.binary = vendored_cucumber_bin # If nil, the gem's binary is used.
+ t.fork = true # You may get faster startup if you set this to false
+ t.profile = 'default'
+ end
+
+ Cucumber::Rake::Task.new({:wip => 'db:test:prepare'}, 'Run features that are being worked on') do |t|
+ t.binary = vendored_cucumber_bin
+ t.fork = true # You may get faster startup if you set this to false
+ t.profile = 'wip'
+ end
+
+ desc 'Run all features'
+ task :all => [:ok, :wip]
+ end
+ desc 'Alias for cucumber:ok'
+ task :cucumber => 'cucumber:ok'
+
+ task :default => :cucumber
+
+ task :features => :cucumber do
+ STDERR.puts "*** The 'features' task is deprecated. See rake -T cucumber ***"
+ end
+rescue LoadError
+ desc 'cucumber rake task not available (cucumber not installed)'
+ task :cucumber do
+ abort 'Cucumber rake task is not available. Be sure to install cucumber as a gem or plugin'
+ end
+end
+
+end
diff --git a/script/cucumber b/script/cucumber
new file mode 100755
index 0000000..7fa5c92
--- /dev/null
+++ b/script/cucumber
@@ -0,0 +1,10 @@
+#!/usr/bin/env ruby
+
+vendored_cucumber_bin = Dir["#{File.dirname(__FILE__)}/../vendor/{gems,plugins}/cucumber*/bin/cucumber"].first
+if vendored_cucumber_bin
+ load File.expand_path(vendored_cucumber_bin)
+else
+ require 'rubygems' unless ENV['NO_RUBYGEMS']
+ require 'cucumber'
+ load Cucumber::BINARY
+end
|
macbury/webpraca
|
067cfeaa8043c6cd344b3450c7f0aca04b00e595
|
Provide some info on missing yml files and give examples
|
diff --git a/.gitignore b/.gitignore
index efb2ba9..dd41b69 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,13 +1,14 @@
.DS_Store
log/*.log
tmp/**/*
public/*.xml.gz
public/images/captchas/*
config/database.yml
config/mailer.yml
config/exception_notifer.yml
+config/exception_notifier.yml
config/website_config.yml
config/micro_feed.yml
config/newrelic.yml
config/deploy.rb
db/*.sqlite3
diff --git a/config/exception_notifier.yml.example b/config/exception_notifier.yml.example
new file mode 100644
index 0000000..ef8d993
--- /dev/null
+++ b/config/exception_notifier.yml.example
@@ -0,0 +1 @@
+production: example@example.org
diff --git a/config/initializers/exception_notifer.rb b/config/initializers/exception_notifer.rb
index 1c64020..1a52455 100644
--- a/config/initializers/exception_notifer.rb
+++ b/config/initializers/exception_notifer.rb
@@ -1 +1,5 @@
-ExceptionNotifier.exception_recipients = YAML.load_file("#{RAILS_ROOT}/config/exception_notifer.yml")[Rails.env]
\ No newline at end of file
+begin
+ ExceptionNotifier.exception_recipients = YAML.load_file(Rails.root.join("config/exception_notifier.yml"))[Rails.env]
+rescue Errno::ENOENT
+ raise "Could not find config/exception_notifier.yml, example is in config/exception_notifier.yml.example"
+end
diff --git a/config/initializers/load_config.rb b/config/initializers/load_config.rb
index 45685f6..c1599b9 100644
--- a/config/initializers/load_config.rb
+++ b/config/initializers/load_config.rb
@@ -1 +1,5 @@
-::WebSiteConfig = StupidSimpleConfig.new("website_config.yml")
\ No newline at end of file
+begin
+ ::WebSiteConfig = StupidSimpleConfig.new("website_config.yml")
+rescue Errno::ENOENT
+ raise "Could not find config/website_config.yml, example is in config/website_config.yml.example"
+end
\ No newline at end of file
diff --git a/config/initializers/mailer.rb b/config/initializers/mailer.rb
index 57fa305..6c3a603 100644
--- a/config/initializers/mailer.rb
+++ b/config/initializers/mailer.rb
@@ -1,8 +1,14 @@
require "smtp_tls"
ActionMailer::Base.delivery_method = :smtp
ActionMailer::Base.default_charset = 'utf-8'
ActionMailer::Base.perform_deliveries = true
-ActionMailer::Base.raise_delivery_errors = true
-ActionMailer::Base.smtp_settings = YAML.load_file("#{RAILS_ROOT}/config/mailer.yml")[Rails.env]
+ActionMailer::Base.raise_delivery_errors = true
+
+begin
+ ActionMailer::Base.smtp_settings = YAML.load_file("#{RAILS_ROOT}/config/mailer.yml")[Rails.env]
+rescue Errno::ENOENT
+ raise "Could not find config/website_config.yml, example is in config/website_config.yml.example"
+end
+
ActionMailer::Base.smtp_settings[:tsl] = true
ActionMailer::Base.smtp_settings[:authentication] = :login
\ No newline at end of file
diff --git a/config/mailer.yml.example b/config/mailer.yml.example
new file mode 100644
index 0000000..9fc0223
--- /dev/null
+++ b/config/mailer.yml.example
@@ -0,0 +1,11 @@
+development: &DEVELOPMENT
+ from: example@example.org
+ address: mail.example.org
+ port: 25
+ user_name: example
+ password: secret
+ authentication: :plain
+ domain: example.org
+production:
+ <<: *DEVELOPMENt
+
diff --git a/config/website_config.yml.example b/config/website_config.yml.example
new file mode 100644
index 0000000..d485f96
--- /dev/null
+++ b/config/website_config.yml.example
@@ -0,0 +1,5 @@
+website:
+ name: My website
+ tags: [ cool, website ]
+ author: Buras Arkadiusz
+ last_update: <%= Time.now %>
|
macbury/webpraca
|
7459fc3b8a29cb29cecab3309d9d7baeed099fde
|
Remove new relic
|
diff --git a/config/environment.rb b/config/environment.rb
index c6ea631..65444dc 100644
--- a/config/environment.rb
+++ b/config/environment.rb
@@ -1,49 +1,48 @@
# Be sure to restart your server when you modify this file
# Specifies gem version of Rails to use when vendor/rails is not present
# Bootstrap the Rails environment, frameworks, and default configuration
require File.join(File.dirname(__FILE__), 'boot')
Rails::Initializer.run do |config|
config.gem 'sitemap_generator', :lib => false, :source => 'http://gemcutter.org'
config.gem 'less', :source => 'http://gemcutter.org', :lib => false
config.gem 'meta-tags', :lib => 'meta_tags', :source => 'http://gemcutter.org'
config.gem 'declarative_authorization'
config.gem 'searchlogic'
config.gem 'RedCloth', :lib => "redcloth"
config.gem 'authlogic'
- config.gem "newrelic_rpm"
config.gem 'whenever', :lib => false, :source => 'http://gemcutter.org/'
config.gem 'highline', :lib => false
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Add additional load paths for your own custom dirs
# config.load_paths += %W( #{RAILS_ROOT}/extras )
# Specify gems that this application depends on and have them installed with rake gems:install
# config.gem "bj"
# config.gem "hpricot", :version => '0.6', :source => "http://code.whytheluckystiff.net"
# config.gem "sqlite3-ruby", :lib => "sqlite3"
# config.gem "aws-s3", :lib => "aws/s3"
# Only load the plugins named here, in the order given (default is alphabetical).
# :all can be used as a placeholder for all plugins not explicitly named
#config.plugins = [ :all, :less, 'less-rails' ]
# Skip frameworks you're not going to use. To use Rails without a database,
# you must remove the Active Record framework.
# config.frameworks -= [ :active_record, :active_resource, :action_mailer ]
# Activate observers that should always be running
# config.active_record.observers = :cacher, :garbage_collector, :forum_observer
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names.
config.time_zone = 'Warsaw'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}')]
config.i18n.default_locale = :pl
end
\ No newline at end of file
|
macbury/webpraca
|
a42064bee3e340f269522f93c3973ee1a9f04a16
|
Email regexp
|
diff --git a/app/models/job.rb b/app/models/job.rb
index 3764913..18573db 100644
--- a/app/models/job.rb
+++ b/app/models/job.rb
@@ -1,176 +1,176 @@
JOB_TYPES = ["zlecenie (konkretna usÅuga do wykonania)", "poszukiwanie wspóÅpracowników / oferta pracy", "wolontariat (praca za reklamy, bannery, itp. lub praca za darmo)", "staż/praktyka"]
JOB_LABELS = ["zlecenie", "etat", "wolontariat", "praktyka"]
JOB_ETAT = 1;
JOB_RANK_VALUES = {
:default => 0.3,
:price => 0.8,
:krs => 0.6,
:nip => 0.5,
:regon => 0.6,
:framework_id => 0.7,
:website => 0.3,
:apply_online => 0.2
}
class Job < ActiveRecord::Base
include ActionController::UrlWriter
xss_terminate
has_permalink :title
named_scope :active, :conditions => ["((jobs.end_at >= ?) AND (jobs.published = ?))", Date.current, true]
named_scope :old, :conditions => ["jobs.end_at < ?", Date.current]
named_scope :has_text, lambda { |text| { :conditions => ["((jobs.title ILIKE ?) OR (jobs.description ILIKE ?))", "%#{text}%", "%#{text}%"] } }
validates_presence_of :title, :description, :email, :company_name, :localization_id, :category_id
validates_length_of :title, :within => 3..255
validates_length_of :description, :within => 10..5000
validates_inclusion_of :type_id, :in => 0..JOB_TYPES.size-1
validates_inclusion_of :dlugosc_trwania, :in => 1..60
validates_numericality_of :price_from,
:greater_than => 0,
:unless => Proc.new { |j| j.price_from.nil? }
validates_numericality_of :price_to,
:greater_than => 0,
:unless => Proc.new { |j| j.price_to.nil? }
- validates_format_of :email, :with => Authlogic::Regex.email
+ validates_format_of :email, :with => /([a-z0-9_.-]+)@([a-z0-9-]+)\.([a-z.]+)/i
validates_format_of :website, :with => /(^$)|(^(http|https):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(([0-9]{1,5})?\/.*)?$)/ix
validates_format_of :regon,
:with => /(^$)|(^[0-9]{7,14}$)/
validates_format_of :nip,
:with => /(^$)|(^\d{2,3}-\d{2,3}-\d{2,3}-\d{2,3}$)/
validates_format_of :krs,
:with => /(^$)|(^\d{10})$/
belongs_to :framework
belongs_to :localization
belongs_to :category
has_many :applicants, :dependent => :delete_all
has_many :visits, :dependent => :delete_all
attr_protected :rank, :permalink, :end_at, :token, :published
attr_accessor :framework_name, :localization_name
before_create :create_from_name, :generate_token
before_save :calculate_rank
after_create :send_notification
def self.find_grouped_by_type
return Job.active.count(:type_id, :group => "type_id")
end
def send_notification
JobMailer.deliver_job_posted(self)
end
def generate_token
alphanumerics = ('a'..'z').to_a.concat(('A'..'Z').to_a.concat(('0'..'9').to_a))
salt = alphanumerics.sort_by{rand}.to_s[0..1024]
self.token = Digest::SHA1.hexdigest("--#{salt}--#{self.id}--#{Date.current}--")
generate_token unless Job.find_by_token(self.token).nil?
end
def calculate_rank
self.rank = 1.0
self.rank += visits_count * 0.01 unless visits_count.nil?
[:regon, :nip, :krs, :framework_id, :website, :apply_online].each do |attribute|
val = send(attribute)
inc = JOB_RANK_VALUES[attribute] || JOB_RANK_VALUES[:default]
self.rank += inc unless (val.nil? || (val.class == String && val.empty?) || (val.class == TrueClass))
end
if widelki_zarobkowe?
self.rank += JOB_RANK_VALUES[:price]
price = price_from || price_to
if price >= 10_000 # ciekawe czy ktoÅ da tyle :P
self.rank += 0.8
elsif price >= 7000
self.rank += 0.7
elsif price >= 5000
self.rank += 0.6
elsif price >= 3000
self.rank += 0.3
elsif price < 2000
if self.type_id == JOB_ETAT
self.rank -= 0.6 # bo nikt za grosze nie chce pracowaÄ
else
self.rank += 0.3 # chyba że to biedny student
end
end
end
end
def widelki_zarobkowe?
((!self.price_from.nil? && self.price_from > 0) || (!self.price_to.nil? && self.price_to > 0))
end
def create_from_name
unless (self.framework_name.nil? || self.framework_name.blank?)
framework = Framework.name_like(self.framework_name).first
framework = Framework.create(:name => self.framework_name) if framework.nil?
self.framework = framework
end
unless (self.localization_name.nil? || self.localization_name.blank?)
localization = Localization.name_like(self.localization_name).first
localization = Localization.create(:name => self.localization_name) if localization.nil?
self.localization = localization
end
end
def dlugosc_trwania
date = created_at.nil? ? Date.current.to_date : created_at.to_date
return (read_attribute(:end_at) - date).to_i rescue 14
end
def dlugosc_trwania=(val)
date = created_at.nil? ? Date.current.to_date : created_at.to_date
write_attribute(:end_at, date+val.to_i.days)
end
def highlited?
self.rank >= 4.75
end
def publish!
self.published = true
save
spawn do
tags = [localization.name, category.name, "praca", JOB_LABELS[self.type_id]]
tags << framework.name unless framework.nil?
MicroFeed.send :streams => :all,
:msg => "[#{company_name}] - #{title}",
:tags => tags,
:link => seo_job_url(self, :host => "webpraca.net")
end
end
def visited_by(ip)
visit = visits.find_or_create_by_ip(IPAddr.new(ip).to_i)
visits_count += 1 if visit.new_record?
save
end
def to_param
permalink
end
end
|
macbury/webpraca
|
c72eae3c65cff08a593e7bd9c3d762b6f8e04c15
|
Pozycjonowanie cz.2
|
diff --git a/app/controllers/jobs_controller.rb b/app/controllers/jobs_controller.rb
index 386605d..9e42994 100644
--- a/app/controllers/jobs_controller.rb
+++ b/app/controllers/jobs_controller.rb
@@ -1,177 +1,178 @@
class JobsController < ApplicationController
validates_captcha :only => [:create, :new]
ads_pos :bottom
ads_pos :right, :except => [:home, :index, :search]
ads_pos :none, :only => [:home]
def home
@page_title = ['najpopularniejsze oferty', 'najnowsze oferty']
query = Job.active.search
@recent_jobs = query.all(:order => "created_at DESC", :limit => 10, :include => [:localization, :category])
@top_jobs = query.all(:order => "rank DESC, created_at DESC", :limit => 10, :include => [:localization, :category])
end
# GET /jobs
# GET /jobs.xml
def index
@query = Job.active.search
options = {
:page => params[:page],
:per_page => 25,
:order => "created_at DESC, rank DESC",
:include => [:localization, :category]
}
if params[:order] =~ /najpopularniejsze/i
@page_title = ['Najpopularniejsze oferty pracy']
@order = :rank
options[:order] = "rank DESC, created_at DESC"
else
@order = :created_at
@page_title = ['Najnowsze oferty pracy']
options[:order] = "created_at DESC, rank DESC"
end
if params[:category]
@category = Category.find_by_permalink!(params[:category])
@page_title << @category.name
@query.category_id_is(@category.id)
end
if params[:localization]
@localization = Localization.find_by_permalink!(params[:localization])
@page_title << @localization.name
@query.localization_id_is(@localization.id)
end
if params[:framework]
@framework = Framework.find_by_permalink!(params[:framework])
@page_title << @framework.name
options[:include] << :framework
@query.framework_id_is(@framework.id)
end
if params[:type_id]
@type_id = JOB_LABELS.index(params[:type_id]) || 0
@page_title << JOB_LABELS[@type_id]
@query.type_id_is(@type_id)
end
@jobs = @query.paginate(options)
respond_to do |format|
format.html # index.html.erb
format.rss
format.atom
end
end
def search
@page_title = ["Szukaj oferty"]
@search = Job.active.search(params[:search])
if params[:search]
@page_title = ["Znalezione oferty"]
@jobs = @search.paginate( :page => params[:page],
:per_page => 30,
:order => "created_at DESC, rank DESC" )
end
respond_to do |format|
format.html
format.rss { render :action => "index" }
format.atom { render :action => "index" }
end
end
# GET /jobs/1
# GET /jobs/1.xml
def show
@job = Job.find_by_permalink!(params[:id])
@job.visited_by(request.remote_ip)
@category = @job.category
@tags = WebSiteConfig['website']['tags'].split(',').map(&:strip) + [@job.category.name, @job.localization.name, @job.company_name]
@tags << @job.framework.name unless @job.framework.nil?
+ @tags << JOB_LABELS[@job.type_id]
set_meta_tags :keywords => @tags.join(', ')
respond_to do |format|
format.html # show.html.erb
end
end
# GET /jobs/new
# GET /jobs/new.xml
def new
@job = Job.new
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @job }
end
end
# POST /jobs
# POST /jobs.xml
def create
@job = Job.new(params[:job])
respond_to do |format|
if @job.save
flash[:notice] = 'Na twój e-mail zostaÅ wysÅany link którym opublikujesz ofertÄ.'
format.html { redirect_to(@job) }
format.xml { render :xml => @job, :status => :created, :location => @job }
else
format.html { render :action => "new" }
format.xml { render :xml => @job.errors, :status => :unprocessable_entity }
end
end
end
# GET /jobs/1/edit
def edit
@job = Job.find_by_permalink_and_token!(params[:id], params[:token])
render :action => "new"
end
# PUT /jobs/1
# PUT /jobs/1.xml
def update
@job = Job.find_by_permalink_and_token!(params[:id], params[:token])
respond_to do |format|
if @job.update_attributes(params[:job])
flash[:notice] = 'Zapisano zmiany w ofercie.'
format.html { redirect_to(@job) }
format.xml { head :ok }
else
format.html { render :action => "new" }
format.xml { render :xml => @job.errors, :status => :unprocessable_entity }
end
end
end
def publish
@job = Job.find_by_permalink_and_token!(params[:id], params[:token])
unless @job.published
@job.publish!
flash[:notice] = "Twoja oferta jest już widoczna!"
end
redirect_to @job
end
# DELETE /jobs/1
# DELETE /jobs/1.xml
def destroy
@job = Job.find_by_permalink_and_token!(params[:id], params[:token])
@job.destroy
flash[:notice] = "Oferta zostaÅa usuniÄta"
respond_to do |format|
format.html { redirect_to(jobs_url) }
format.xml { head :ok }
end
end
end
|
macbury/webpraca
|
6dca450eafe68dc99bbb8d828ffcad29c4a9ff6b
|
Pozycjonowanie
|
diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb
index e39d520..ee5a137 100644
--- a/app/controllers/application_controller.rb
+++ b/app/controllers/application_controller.rb
@@ -1,118 +1,117 @@
class ApplicationController < ActionController::Base
include ExceptionNotifiable
helper :all # include all helpers, all the time
protect_from_forgery # See ActionController::RequestForgeryProtection for details
filter_parameter_logging :password, :password_confirmation
helper_method :current_user_session, :current_user, :logged_in?, :own?
before_filter :staging_authentication, :seo, :user_for_authorization
def rescue_action_in_public(exception)
case exception
when ActiveRecord::RecordNotFound
render_404
when ActionController::RoutingError
render_404
when ActionController::UnknownController
render_404
when ActionController::UnknownAction
render_404
else
render_500
end
end
protected
def render_404
@page_title = ["BÅÄ
d 404", "Nie znaleziono strony"]
render :template => "shared/error_404", :layout => 'application', :status => :not_found
end
def render_500
@page_title = ["BÅÄ
d 500", "CoÅ poszÅo nie tak"]
render :template => "shared/error_500", :layout => 'application', :status => :internal_server_error
end
def not_for_production
redirect_to root_path if Rails.env == "production"
end
# Ads Position
# :bottom, :right, :none
def self.ads_pos(position, options = {})
before_filter(options) do |controller|
controller.instance_variable_set('@ads_pos', position)
end
end
def user_for_authorization
Authorization.current_user = self.current_user
end
def permission_denied
flash[:error] = "Nie masz wystarczajÄ
cych uprawnieÅ aby móc odwiedziÄ tÄ
stronÄ"
redirect_to root_url
end
def seo
@ads_pos = :bottom
- @standard_tags = WebSiteConfig['website']['tags']
set_meta_tags :description => WebSiteConfig['website']['description'],
- :keywords => @standard_tags
+ :keywords => WebSiteConfig['website']['tags']
end
def staging_authentication
if ENV['RAILS_ENV'] == 'staging'
authenticate_or_request_with_http_basic do |user_name, password|
user_name == "change this" && password == "and this"
end
end
end
def current_user_session
@current_user_session ||= UserSession.find
return @current_user_session
end
def current_user
@current_user ||= self.current_user_session && self.current_user_session.user
return @current_user
end
def logged_in?
!self.current_user.nil?
end
def own?(object)
logged_in? && self.current_user.own?(object)
end
def store_location
session[:return_to] = request.request_uri
end
def redirect_back_or_default
redirect_to session[:return_to] || admin_path
session[:return_to] = nil
end
def login_required
unless logged_in?
respond_to do |format|
format.html do
flash[:error] = "Musisz siÄ zalogowaÄ aby móc objrzeÄ tÄ
strone"
store_location
redirect_to login_path
end
format.js { render :js => "window.location = #{login_path.inspect};" }
end
else
@page_title = ["Panel administracyjny"]
end
end
end
\ No newline at end of file
diff --git a/app/controllers/jobs_controller.rb b/app/controllers/jobs_controller.rb
index 27aa352..386605d 100644
--- a/app/controllers/jobs_controller.rb
+++ b/app/controllers/jobs_controller.rb
@@ -1,171 +1,177 @@
class JobsController < ApplicationController
validates_captcha :only => [:create, :new]
ads_pos :bottom
ads_pos :right, :except => [:home, :index, :search]
ads_pos :none, :only => [:home]
def home
@page_title = ['najpopularniejsze oferty', 'najnowsze oferty']
query = Job.active.search
@recent_jobs = query.all(:order => "created_at DESC", :limit => 10, :include => [:localization, :category])
@top_jobs = query.all(:order => "rank DESC, created_at DESC", :limit => 10, :include => [:localization, :category])
end
# GET /jobs
# GET /jobs.xml
def index
@query = Job.active.search
options = {
:page => params[:page],
:per_page => 25,
:order => "created_at DESC, rank DESC",
:include => [:localization, :category]
}
if params[:order] =~ /najpopularniejsze/i
@page_title = ['Najpopularniejsze oferty pracy']
@order = :rank
options[:order] = "rank DESC, created_at DESC"
else
@order = :created_at
@page_title = ['Najnowsze oferty pracy']
options[:order] = "created_at DESC, rank DESC"
end
if params[:category]
@category = Category.find_by_permalink!(params[:category])
@page_title << @category.name
@query.category_id_is(@category.id)
end
if params[:localization]
@localization = Localization.find_by_permalink!(params[:localization])
@page_title << @localization.name
@query.localization_id_is(@localization.id)
end
if params[:framework]
@framework = Framework.find_by_permalink!(params[:framework])
@page_title << @framework.name
options[:include] << :framework
@query.framework_id_is(@framework.id)
end
if params[:type_id]
@type_id = JOB_LABELS.index(params[:type_id]) || 0
@page_title << JOB_LABELS[@type_id]
@query.type_id_is(@type_id)
end
@jobs = @query.paginate(options)
respond_to do |format|
format.html # index.html.erb
format.rss
format.atom
end
end
def search
@page_title = ["Szukaj oferty"]
@search = Job.active.search(params[:search])
if params[:search]
@page_title = ["Znalezione oferty"]
@jobs = @search.paginate( :page => params[:page],
:per_page => 30,
:order => "created_at DESC, rank DESC" )
end
respond_to do |format|
format.html
format.rss { render :action => "index" }
format.atom { render :action => "index" }
end
end
# GET /jobs/1
# GET /jobs/1.xml
def show
@job = Job.find_by_permalink!(params[:id])
@job.visited_by(request.remote_ip)
@category = @job.category
+
+ @tags = WebSiteConfig['website']['tags'].split(',').map(&:strip) + [@job.category.name, @job.localization.name, @job.company_name]
+ @tags << @job.framework.name unless @job.framework.nil?
+
+ set_meta_tags :keywords => @tags.join(', ')
+
respond_to do |format|
format.html # show.html.erb
end
end
# GET /jobs/new
# GET /jobs/new.xml
def new
@job = Job.new
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @job }
end
end
# POST /jobs
# POST /jobs.xml
def create
@job = Job.new(params[:job])
respond_to do |format|
if @job.save
flash[:notice] = 'Na twój e-mail zostaÅ wysÅany link którym opublikujesz ofertÄ.'
format.html { redirect_to(@job) }
format.xml { render :xml => @job, :status => :created, :location => @job }
else
format.html { render :action => "new" }
format.xml { render :xml => @job.errors, :status => :unprocessable_entity }
end
end
end
# GET /jobs/1/edit
def edit
@job = Job.find_by_permalink_and_token!(params[:id], params[:token])
render :action => "new"
end
# PUT /jobs/1
# PUT /jobs/1.xml
def update
@job = Job.find_by_permalink_and_token!(params[:id], params[:token])
respond_to do |format|
if @job.update_attributes(params[:job])
flash[:notice] = 'Zapisano zmiany w ofercie.'
format.html { redirect_to(@job) }
format.xml { head :ok }
else
format.html { render :action => "new" }
format.xml { render :xml => @job.errors, :status => :unprocessable_entity }
end
end
end
def publish
@job = Job.find_by_permalink_and_token!(params[:id], params[:token])
unless @job.published
@job.publish!
flash[:notice] = "Twoja oferta jest już widoczna!"
end
redirect_to @job
end
# DELETE /jobs/1
# DELETE /jobs/1.xml
def destroy
@job = Job.find_by_permalink_and_token!(params[:id], params[:token])
@job.destroy
flash[:notice] = "Oferta zostaÅa usuniÄta"
respond_to do |format|
format.html { redirect_to(jobs_url) }
format.xml { head :ok }
end
end
end
diff --git a/app/views/jobs/show.html.erb b/app/views/jobs/show.html.erb
index 01a6db5..778f988 100644
--- a/app/views/jobs/show.html.erb
+++ b/app/views/jobs/show.html.erb
@@ -1,84 +1,84 @@
<% title [@job.category.name, @job.localization.name, @job.company_name, @job.title] %>
<div class="box">
<div>
<div class="title">
<h2>
<%= @job.title %>
</h2>
</div>
<dl>
<dt>Typ</dt>
<dd><%= job_label(@job) %></dd>
<dt>Kategoria</dt>
<dd><%= link_to @job.category.name, job_category_path(@job.category) %></dd>
<dt>Ocena</dt>
<dd><%= format_rank(@job.rank) %></dd>
<dt>Pracodawca</dt>
<dd><%= link_to @job.company_name, @job.website, :target => "_blank" %></dd>
<dt>Lokalizacja</dt>
<dd><%= link_to @job.localization.name, localization_path(@job.localization) %></dd>
<% unless @job.framework.nil? %>
<dt>Framework</dt>
<dd><%= link_to @job.framework.name, framework_path(@job.framework) %></dd>
<% end %>
<% if @job.widelki_zarobkowe? %>
<dt>WideÅko zarobkowe</dt>
<dd>
<%= "od #{number_to_currency(@job.price_from)}" unless @job.price_from.nil? %>
<%= "do #{number_to_currency(@job.price_to)}" unless @job.price_to.nil? %> na miesiÄ
c, netto
</dd>
<% end %>
<% unless @job.apply_online %>
<dt>Kontakt</dt>
<dd><%= link_to "Formularz kontaktowy", contact_path(:job_id => @job.id) %></dd>
<% end %>
<% unless (@job.regon.nil? || @job.regon.empty?) %>
<dt>REGON</dt>
<dd><%= @job.regon %> </dd>
<% end %>
<% unless (@job.nip.nil? || @job.nip.empty?) %>
<dt>NIP</dt>
<dd><%= @job.nip %> </dd>
<% end %>
<% unless (@job.krs.nil? || @job.krs.empty?) %>
<dt>KRS</dt>
<dd><%= link_to @job.krs, "http://krs.ms.gov.pl/Podmiot.aspx?nrkrs=#{@job.krs}", :target => "_blank" %> </dd>
<% end %>
<dt>Data rozpoczÄcia</dt>
<dd>
<%= l @job.created_at, :format => :long %>
<br />
<abbr title="<%= @job.created_at.xmlschema %>"><%= distance_of_time_in_words_to_now @job.created_at %> temu</abbr>
</dd>
<dt>Data zakoÅczenia</dt>
<dd>
<%= l @job.end_at, :format => :long %>
<br />
za <abbr title="<%= @job.end_at.xmlschema %>"><%= distance_of_time_in_words_to_now(@job.end_at) %></abbr>
</dd>
<dt>WyÅwietlona</dt>
<dd><%= @job.visits_count %> razy</dd>
</dl>
<div class="clear"></div>
</div>
<div>
<div class="title mini">
<h3>Opis oferty</h3>
</div>
<div class="text">
- <%= RedCloth.new(@job.description).to_html %>
+ <%= RedCloth.new(highlight(@job.description, @tags, :highlighter => '<i>\1</i>')).to_html %>
</div>
<p>
<% if permitted_to? :edit, @job %>
<%= link_to 'Edytuj', edit_job_path(@job) %> |
<%= link_to 'Wstecz', jobs_path %>
<% end %>
</p>
</div>
<%= link_to 'Aplikuj online!', new_job_applicant_path(@job), :class => "more" if @job.apply_online %>
</div>
|
macbury/webpraca
|
6a63cb22f9b60adebab6f9328df552cb224da814
|
Dodanie tagow
|
diff --git a/app/models/job.rb b/app/models/job.rb
index 23d0937..3764913 100644
--- a/app/models/job.rb
+++ b/app/models/job.rb
@@ -1,176 +1,176 @@
JOB_TYPES = ["zlecenie (konkretna usÅuga do wykonania)", "poszukiwanie wspóÅpracowników / oferta pracy", "wolontariat (praca za reklamy, bannery, itp. lub praca za darmo)", "staż/praktyka"]
JOB_LABELS = ["zlecenie", "etat", "wolontariat", "praktyka"]
JOB_ETAT = 1;
JOB_RANK_VALUES = {
:default => 0.3,
:price => 0.8,
:krs => 0.6,
:nip => 0.5,
:regon => 0.6,
:framework_id => 0.7,
:website => 0.3,
:apply_online => 0.2
}
class Job < ActiveRecord::Base
include ActionController::UrlWriter
xss_terminate
has_permalink :title
named_scope :active, :conditions => ["((jobs.end_at >= ?) AND (jobs.published = ?))", Date.current, true]
named_scope :old, :conditions => ["jobs.end_at < ?", Date.current]
named_scope :has_text, lambda { |text| { :conditions => ["((jobs.title ILIKE ?) OR (jobs.description ILIKE ?))", "%#{text}%", "%#{text}%"] } }
validates_presence_of :title, :description, :email, :company_name, :localization_id, :category_id
validates_length_of :title, :within => 3..255
validates_length_of :description, :within => 10..5000
validates_inclusion_of :type_id, :in => 0..JOB_TYPES.size-1
validates_inclusion_of :dlugosc_trwania, :in => 1..60
validates_numericality_of :price_from,
:greater_than => 0,
:unless => Proc.new { |j| j.price_from.nil? }
validates_numericality_of :price_to,
:greater_than => 0,
:unless => Proc.new { |j| j.price_to.nil? }
validates_format_of :email, :with => Authlogic::Regex.email
validates_format_of :website, :with => /(^$)|(^(http|https):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(([0-9]{1,5})?\/.*)?$)/ix
validates_format_of :regon,
:with => /(^$)|(^[0-9]{7,14}$)/
validates_format_of :nip,
:with => /(^$)|(^\d{2,3}-\d{2,3}-\d{2,3}-\d{2,3}$)/
validates_format_of :krs,
:with => /(^$)|(^\d{10})$/
belongs_to :framework
belongs_to :localization
belongs_to :category
has_many :applicants, :dependent => :delete_all
has_many :visits, :dependent => :delete_all
attr_protected :rank, :permalink, :end_at, :token, :published
attr_accessor :framework_name, :localization_name
before_create :create_from_name, :generate_token
before_save :calculate_rank
after_create :send_notification
def self.find_grouped_by_type
return Job.active.count(:type_id, :group => "type_id")
end
def send_notification
JobMailer.deliver_job_posted(self)
end
def generate_token
alphanumerics = ('a'..'z').to_a.concat(('A'..'Z').to_a.concat(('0'..'9').to_a))
salt = alphanumerics.sort_by{rand}.to_s[0..1024]
self.token = Digest::SHA1.hexdigest("--#{salt}--#{self.id}--#{Date.current}--")
generate_token unless Job.find_by_token(self.token).nil?
end
def calculate_rank
self.rank = 1.0
self.rank += visits_count * 0.01 unless visits_count.nil?
[:regon, :nip, :krs, :framework_id, :website, :apply_online].each do |attribute|
val = send(attribute)
inc = JOB_RANK_VALUES[attribute] || JOB_RANK_VALUES[:default]
self.rank += inc unless (val.nil? || (val.class == String && val.empty?) || (val.class == TrueClass))
end
if widelki_zarobkowe?
self.rank += JOB_RANK_VALUES[:price]
price = price_from || price_to
if price >= 10_000 # ciekawe czy ktoÅ da tyle :P
self.rank += 0.8
elsif price >= 7000
self.rank += 0.7
elsif price >= 5000
self.rank += 0.6
elsif price >= 3000
self.rank += 0.3
elsif price < 2000
if self.type_id == JOB_ETAT
self.rank -= 0.6 # bo nikt za grosze nie chce pracowaÄ
else
self.rank += 0.3 # chyba że to biedny student
end
end
end
end
def widelki_zarobkowe?
((!self.price_from.nil? && self.price_from > 0) || (!self.price_to.nil? && self.price_to > 0))
end
def create_from_name
unless (self.framework_name.nil? || self.framework_name.blank?)
framework = Framework.name_like(self.framework_name).first
framework = Framework.create(:name => self.framework_name) if framework.nil?
self.framework = framework
end
unless (self.localization_name.nil? || self.localization_name.blank?)
localization = Localization.name_like(self.localization_name).first
localization = Localization.create(:name => self.localization_name) if localization.nil?
self.localization = localization
end
end
def dlugosc_trwania
date = created_at.nil? ? Date.current.to_date : created_at.to_date
return (read_attribute(:end_at) - date).to_i rescue 14
end
def dlugosc_trwania=(val)
date = created_at.nil? ? Date.current.to_date : created_at.to_date
write_attribute(:end_at, date+val.to_i.days)
end
def highlited?
self.rank >= 4.75
end
def publish!
self.published = true
save
spawn do
- tags = [localization.name, category.name]
+ tags = [localization.name, category.name, "praca", JOB_LABELS[self.type_id]]
tags << framework.name unless framework.nil?
MicroFeed.send :streams => :all,
:msg => "[#{company_name}] - #{title}",
:tags => tags,
:link => seo_job_url(self, :host => "webpraca.net")
end
end
def visited_by(ip)
visit = visits.find_or_create_by_ip(IPAddr.new(ip).to_i)
visits_count += 1 if visit.new_record?
save
end
def to_param
permalink
end
end
|
macbury/webpraca
|
d1c00a602fe2ebc296fb76195b725a8e9fc052c6
|
Ignore website config
|
diff --git a/.gitignore b/.gitignore
index bdfc986..efb2ba9 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,12 +1,13 @@
.DS_Store
log/*.log
tmp/**/*
public/*.xml.gz
public/images/captchas/*
config/database.yml
config/mailer.yml
config/exception_notifer.yml
+config/website_config.yml
config/micro_feed.yml
config/newrelic.yml
config/deploy.rb
db/*.sqlite3
|
macbury/webpraca
|
6ab5484183127207201c95c77594c3b6c26aa02f
|
Flaker i sugester
|
diff --git a/app/views/layouts/application.html.erb b/app/views/layouts/application.html.erb
index ca4113d..7267aca 100644
--- a/app/views/layouts/application.html.erb
+++ b/app/views/layouts/application.html.erb
@@ -1,89 +1,91 @@
<!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" lang="pl">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="google-site-verification" content="zE20xzrx6CCNbFsmsNTok9xaPavS0Cmu7hJxdUbNqN8" />
<%= display_meta_tags :site => WebSiteConfig['website']['name'] %>
<meta name="viewport" content="width=900" />
<%= rss_link("RSS", jobs_url(:format => :rss)) %>
<%= rss_link("ATOM", jobs_url(:format => :atom)) %>
<%= javascript_tag "window._token = '#{form_authenticity_token}'" %>
<%= javascript_include_merged :base %>
<%= stylesheet_link_merged :base %>
</head>
<body>
<div class="wrapper">
<div class="header">
<h1 id="logo"><%= link_to WebSiteConfig['website']['name'], root_path %></h1>
<ul class="categories">
<li class="right">
<%= link_to "Najpopularniejsze", seo_jobs_path(:order => 'najpopularniejsze', :category => params[:category]), :class => (!@order.nil? && @order == :rank) ? "selected" : "normal" %>
</li>
<li class="right">
<%= link_to "Najnowsze", seo_jobs_path(:order => 'najnowsze', :category => params[:category] ), :class => (!@order.nil? && @order == :created_at) ? "selected" : "normal" %>
</li>
<% for category in Category.all(:order => "position") %>
<li>
<%= link_to category.name, seo_jobs_path(:order => params[:order], :category => category.permalink), :class => (!@category.nil? && @category.id == category.id) ? "selected" : "normal" %>
</li>
<% end %>
</ul>
<ul class="menu">
<li><%= link_to "Strona gÅówna", root_path %></li>
<li><%= link_to "Szukaj", search_jobs_path %></li>
<li><%= link_to "Informacje", "/strona/informacje/" %></li>
<li><%= link_to "Regulamin", "/strona/regulamin/" %></li>
<li><%= link_to "Obserwuj nas", "/strona/obserwuj-nas" %></li>
<li><%= link_to "Kontakt", contact_path %></li>
</ul>
</div>
<%- flash.each do |name, msg| -%>
<div class="<%= "flash #{name}" %>">
<a href="#" class="dismiss">X</a>
<p><%= msg %></p>
</div>
<%- end -%>
<div class="sidebar">
<div class="box">
<%= link_to "Dodaj ofertÄ za DARMO!", new_job_path, :id => "add_job", :class => "more" %>
</div>
<%= yield :sidebar %>
<% if @ads_pos == :right %>
<div class="box">
<div>
<%= render :partial => "/shared/ads" %>
</div>
</div>
<% end %>
</div>
<div class="content">
<%= yield %>
<% if @ads_pos == :bottom %>
<div class="box">
<div>
<%= render :partial => "/shared/ads" %>
</div>
</div>
<% end %>
</div>
<div class="clear"></div>
</div>
<%= render :partial => "/shared/footer" %>
+ <script type="text/javascript" src="http://flaker.pl/track/site/1122612"></script>
+ <script type="text/javascript" src="http://app.sugester.pl/webpraca/widget.js"></script>
<script type="text/javascript">
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script>
<script type="text/javascript">
try {
var pageTracker = _gat._getTracker("UA-11469054-5");
pageTracker._trackPageview();
} catch(err) {}</script>
</body>
</html>
\ No newline at end of file
|
macbury/webpraca
|
28b6bb71e0a6dcd9ec2a51c3749670edd47fd174
|
Captchas
|
diff --git a/config/schedule.rb b/config/schedule.rb
index ae8f42e..e064fe2 100644
--- a/config/schedule.rb
+++ b/config/schedule.rb
@@ -1,12 +1,13 @@
set :environment, "production"
set :output, '/home/webpraca/www/apps/webpraca/shared/log/cron.log'
env :GEM_PATH, '/home/webpraca/www/.ruby/gems/1.8:/var/lib/gems/1.8/'
-every 1.hour do # Many shortcuts available: :hour, :day, :month, :year, :reboot
- rake "validates_captcha:create_static_images COUNT=50"
+every 1.day, :at => '1:00 am' do
+ rake "validates_captcha:create_static_images COUNT=500"
+ command "restart-app webpraca"
end
every 1.day, :at => '1:30 am' do
rake "webpraca:jobs:remove_old"
rake "sitemap:refresh"
end
\ No newline at end of file
|
macbury/webpraca
|
7dda097e31e2665ea4325b4bd9fdd2e2b74dc924
|
Google
|
diff --git a/app/views/layouts/application.html.erb b/app/views/layouts/application.html.erb
index 587326d..ca4113d 100644
--- a/app/views/layouts/application.html.erb
+++ b/app/views/layouts/application.html.erb
@@ -1,88 +1,89 @@
<!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" lang="pl">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
+ <meta name="google-site-verification" content="zE20xzrx6CCNbFsmsNTok9xaPavS0Cmu7hJxdUbNqN8" />
<%= display_meta_tags :site => WebSiteConfig['website']['name'] %>
<meta name="viewport" content="width=900" />
<%= rss_link("RSS", jobs_url(:format => :rss)) %>
<%= rss_link("ATOM", jobs_url(:format => :atom)) %>
<%= javascript_tag "window._token = '#{form_authenticity_token}'" %>
<%= javascript_include_merged :base %>
<%= stylesheet_link_merged :base %>
</head>
<body>
<div class="wrapper">
<div class="header">
<h1 id="logo"><%= link_to WebSiteConfig['website']['name'], root_path %></h1>
<ul class="categories">
<li class="right">
<%= link_to "Najpopularniejsze", seo_jobs_path(:order => 'najpopularniejsze', :category => params[:category]), :class => (!@order.nil? && @order == :rank) ? "selected" : "normal" %>
</li>
<li class="right">
<%= link_to "Najnowsze", seo_jobs_path(:order => 'najnowsze', :category => params[:category] ), :class => (!@order.nil? && @order == :created_at) ? "selected" : "normal" %>
</li>
<% for category in Category.all(:order => "position") %>
<li>
<%= link_to category.name, seo_jobs_path(:order => params[:order], :category => category.permalink), :class => (!@category.nil? && @category.id == category.id) ? "selected" : "normal" %>
</li>
<% end %>
</ul>
<ul class="menu">
<li><%= link_to "Strona gÅówna", root_path %></li>
<li><%= link_to "Szukaj", search_jobs_path %></li>
<li><%= link_to "Informacje", "/strona/informacje/" %></li>
<li><%= link_to "Regulamin", "/strona/regulamin/" %></li>
<li><%= link_to "Obserwuj nas", "/strona/obserwuj-nas" %></li>
<li><%= link_to "Kontakt", contact_path %></li>
</ul>
</div>
<%- flash.each do |name, msg| -%>
<div class="<%= "flash #{name}" %>">
<a href="#" class="dismiss">X</a>
<p><%= msg %></p>
</div>
<%- end -%>
<div class="sidebar">
<div class="box">
<%= link_to "Dodaj ofertÄ za DARMO!", new_job_path, :id => "add_job", :class => "more" %>
</div>
<%= yield :sidebar %>
<% if @ads_pos == :right %>
<div class="box">
<div>
<%= render :partial => "/shared/ads" %>
</div>
</div>
<% end %>
</div>
<div class="content">
<%= yield %>
<% if @ads_pos == :bottom %>
<div class="box">
<div>
<%= render :partial => "/shared/ads" %>
</div>
</div>
<% end %>
</div>
<div class="clear"></div>
</div>
<%= render :partial => "/shared/footer" %>
<script type="text/javascript">
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script>
<script type="text/javascript">
try {
var pageTracker = _gat._getTracker("UA-11469054-5");
pageTracker._trackPageview();
} catch(err) {}</script>
</body>
</html>
\ No newline at end of file
|
macbury/webpraca
|
160f6178dd48fd65e960dc3efc11c86e569522ca
|
google-analytics
|
diff --git a/app/views/layouts/application.html.erb b/app/views/layouts/application.html.erb
index da46472..587326d 100644
--- a/app/views/layouts/application.html.erb
+++ b/app/views/layouts/application.html.erb
@@ -1,80 +1,88 @@
<!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" lang="pl">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<%= display_meta_tags :site => WebSiteConfig['website']['name'] %>
<meta name="viewport" content="width=900" />
<%= rss_link("RSS", jobs_url(:format => :rss)) %>
<%= rss_link("ATOM", jobs_url(:format => :atom)) %>
<%= javascript_tag "window._token = '#{form_authenticity_token}'" %>
<%= javascript_include_merged :base %>
<%= stylesheet_link_merged :base %>
</head>
<body>
<div class="wrapper">
<div class="header">
<h1 id="logo"><%= link_to WebSiteConfig['website']['name'], root_path %></h1>
<ul class="categories">
<li class="right">
<%= link_to "Najpopularniejsze", seo_jobs_path(:order => 'najpopularniejsze', :category => params[:category]), :class => (!@order.nil? && @order == :rank) ? "selected" : "normal" %>
</li>
<li class="right">
<%= link_to "Najnowsze", seo_jobs_path(:order => 'najnowsze', :category => params[:category] ), :class => (!@order.nil? && @order == :created_at) ? "selected" : "normal" %>
</li>
<% for category in Category.all(:order => "position") %>
<li>
<%= link_to category.name, seo_jobs_path(:order => params[:order], :category => category.permalink), :class => (!@category.nil? && @category.id == category.id) ? "selected" : "normal" %>
</li>
<% end %>
</ul>
<ul class="menu">
<li><%= link_to "Strona gÅówna", root_path %></li>
<li><%= link_to "Szukaj", search_jobs_path %></li>
<li><%= link_to "Informacje", "/strona/informacje/" %></li>
<li><%= link_to "Regulamin", "/strona/regulamin/" %></li>
<li><%= link_to "Obserwuj nas", "/strona/obserwuj-nas" %></li>
<li><%= link_to "Kontakt", contact_path %></li>
</ul>
</div>
<%- flash.each do |name, msg| -%>
<div class="<%= "flash #{name}" %>">
<a href="#" class="dismiss">X</a>
<p><%= msg %></p>
</div>
<%- end -%>
<div class="sidebar">
<div class="box">
<%= link_to "Dodaj ofertÄ za DARMO!", new_job_path, :id => "add_job", :class => "more" %>
</div>
<%= yield :sidebar %>
<% if @ads_pos == :right %>
<div class="box">
<div>
<%= render :partial => "/shared/ads" %>
</div>
</div>
<% end %>
</div>
<div class="content">
<%= yield %>
<% if @ads_pos == :bottom %>
<div class="box">
<div>
<%= render :partial => "/shared/ads" %>
</div>
</div>
<% end %>
</div>
<div class="clear"></div>
</div>
<%= render :partial => "/shared/footer" %>
- <%= WebSiteConfig['js']['google_analytics'] %>
+ <script type="text/javascript">
+ var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
+ document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
+ </script>
+ <script type="text/javascript">
+ try {
+ var pageTracker = _gat._getTracker("UA-11469054-5");
+ pageTracker._trackPageview();
+ } catch(err) {}</script>
</body>
</html>
\ No newline at end of file
|
macbury/webpraca
|
50c8240c6e6ab69b871b81d03525452e44990242
|
Publish task
|
diff --git a/lib/tasks/webpraca.rake b/lib/tasks/webpraca.rake
index da7bc38..9afcbcc 100644
--- a/lib/tasks/webpraca.rake
+++ b/lib/tasks/webpraca.rake
@@ -1,68 +1,74 @@
require 'highline/import'
def ask_for_password(message)
val = ask(message) {|q| q.echo = false}
if val.nil? || val.empty?
return ask_for_password(message)
else
return val
end
end
def ask(message)
puts "#{message}:"
val = STDIN.gets.chomp
if val.nil? || val.empty?
return ask(message)
else
return val
end
end
def render_errors(obj)
index = 0
obj.errors.each_full do |msg|
index += 1
puts "#{index}. #{msg}"
end
end
namespace :webpraca do
namespace :clear do
task :applicants => :environment do
Applicant.all.each(&:destroy)
end
task :visits => :environment do
Visit.all.each(&:destroy)
end
end
namespace :jobs do
task :remove_old => :environment do
Job.old.each(&:destroy)
end
task :publish_all => :environment do
Job.all(:conditions => { :published => false }).each do |job|
job.send_notification
job.publish!
end
end
+
+ task :publish => :environment do
+ Job.all(:conditions => { :published => nil }).each do |job|
+ job.publish!
+ end
+ end
end
namespace :admin do
task :create => :environment do
puts "Creating new admin user"
user = User.new
user.email = ask("Enter E-Mail")
user.password = ask_for_password("Enter Password")
user.password_confirmation = ask_for_password("Enter password confirmation")
if user.save
puts "Created admin user!"
else
render_errors(user)
end
end
end
end
\ No newline at end of file
|
macbury/webpraca
|
e4853cfdaef8d0156bc4f2853a5863c584ca1422
|
REmove spawn
|
diff --git a/app/models/job.rb b/app/models/job.rb
index 555d2c5..233865d 100644
--- a/app/models/job.rb
+++ b/app/models/job.rb
@@ -1,176 +1,176 @@
JOB_TYPES = ["zlecenie (konkretna usÅuga do wykonania)", "poszukiwanie wspóÅpracowników / oferta pracy", "wolontariat (praca za reklamy, bannery, itp. lub praca za darmo)", "staż/praktyka"]
JOB_LABELS = ["zlecenie", "etat", "wolontariat", "praktyka"]
JOB_ETAT = 1;
JOB_RANK_VALUES = {
:default => 0.3,
:price => 0.8,
:krs => 0.6,
:nip => 0.5,
:regon => 0.6,
:framework_id => 0.7,
:website => 0.3,
:apply_online => 0.2
}
class Job < ActiveRecord::Base
include ActionController::UrlWriter
xss_terminate
has_permalink :title
named_scope :active, :conditions => ["((jobs.end_at >= ?) AND (jobs.published = ?))", Date.current, true]
named_scope :old, :conditions => ["jobs.end_at < ?", Date.current]
named_scope :has_text, lambda { |text| { :conditions => ["((jobs.title ILIKE ?) OR (jobs.description ILIKE ?))", "%#{text}%", "%#{text}%"] } }
validates_presence_of :title, :description, :email, :company_name, :localization_id, :category_id
validates_length_of :title, :within => 3..255
validates_length_of :description, :within => 10..5000
validates_inclusion_of :type_id, :in => 0..JOB_TYPES.size-1
validates_inclusion_of :dlugosc_trwania, :in => 1..60
validates_numericality_of :price_from,
:greater_than => 0,
:unless => Proc.new { |j| j.price_from.nil? }
validates_numericality_of :price_to,
:greater_than => 0,
:unless => Proc.new { |j| j.price_to.nil? }
validates_format_of :email, :with => Authlogic::Regex.email
validates_format_of :website, :with => /(^$)|(^(http|https):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(([0-9]{1,5})?\/.*)?$)/ix
validates_format_of :regon,
:with => /(^$)|(^[0-9]{7,14}$)/
validates_format_of :nip,
:with => /(^$)|(^\d{2,3}-\d{2,3}-\d{2,3}-\d{2,3}$)/
validates_format_of :krs,
:with => /(^$)|(^\d{10})$/
belongs_to :framework
belongs_to :localization
belongs_to :category
has_many :applicants, :dependent => :delete_all
has_many :visits, :dependent => :delete_all
attr_protected :rank, :permalink, :end_at, :token, :published
attr_accessor :framework_name, :localization_name
before_create :create_from_name, :generate_token
before_save :calculate_rank
after_create :send_notification
def self.find_grouped_by_type
return Job.active.count(:type_id, :group => "type_id")
end
def send_notification
JobMailer.deliver_job_posted(self)
end
def generate_token
alphanumerics = ('a'..'z').to_a.concat(('A'..'Z').to_a.concat(('0'..'9').to_a))
salt = alphanumerics.sort_by{rand}.to_s[0..1024]
self.token = Digest::SHA1.hexdigest("--#{salt}--#{self.id}--#{Date.current}--")
generate_token unless Job.find_by_token(self.token).nil?
end
def calculate_rank
self.rank = 1.0
self.rank += visits_count * 0.01 unless visits_count.nil?
[:regon, :nip, :krs, :framework_id, :website, :apply_online].each do |attribute|
val = send(attribute)
inc = JOB_RANK_VALUES[attribute] || JOB_RANK_VALUES[:default]
self.rank += inc unless (val.nil? || (val.class == String && val.empty?) || (val.class == TrueClass))
end
if widelki_zarobkowe?
self.rank += JOB_RANK_VALUES[:price]
price = price_from || price_to
if price >= 10_000 # ciekawe czy ktoÅ da tyle :P
self.rank += 0.8
elsif price >= 7000
self.rank += 0.7
elsif price >= 5000
self.rank += 0.6
elsif price >= 3000
self.rank += 0.3
elsif price < 2000
if self.type_id == JOB_ETAT
self.rank -= 0.6 # bo nikt za grosze nie chce pracowaÄ
else
self.rank += 0.3 # chyba że to biedny student
end
end
end
end
def widelki_zarobkowe?
((!self.price_from.nil? && self.price_from > 0) || (!self.price_to.nil? && self.price_to > 0))
end
def create_from_name
unless (self.framework_name.nil? || self.framework_name.blank?)
framework = Framework.name_like(self.framework_name).first
framework = Framework.create(:name => self.framework_name) if framework.nil?
self.framework = framework
end
unless (self.localization_name.nil? || self.localization_name.blank?)
localization = Localization.name_like(self.localization_name).first
localization = Localization.create(:name => self.localization_name) if localization.nil?
self.localization = localization
end
end
def dlugosc_trwania
date = created_at.nil? ? Date.current.to_date : created_at.to_date
return (read_attribute(:end_at) - date).to_i rescue 14
end
def dlugosc_trwania=(val)
date = created_at.nil? ? Date.current.to_date : created_at.to_date
write_attribute(:end_at, date+val.to_i.days)
end
def highlited?
self.rank >= 4.75
end
def publish!
self.published = true
save
- spawn do
+
tags = [localization.name, category.name]
tags << framework.name unless framework.nil?
MicroFeed.send :streams => :all,
:msg => "[#{company_name}] - #{title}",
:tags => tags,
:link => seo_job_url(job, :host => "webpraca.net")
- end
+
end
def visited_by(ip)
visit = visits.find_or_create_by_ip(IPAddr.new(ip).to_i)
visits_count += 1 if visit.new_record?
save
end
def to_param
permalink
end
end
|
macbury/webpraca
|
7a662a71f841d63b021b3d088c5bf1561d9d8c04
|
Cron shedule
|
diff --git a/config/schedule.rb b/config/schedule.rb
index d8a28fc..ae8f42e 100644
--- a/config/schedule.rb
+++ b/config/schedule.rb
@@ -1,12 +1,12 @@
set :environment, "production"
set :output, '/home/webpraca/www/apps/webpraca/shared/log/cron.log'
env :GEM_PATH, '/home/webpraca/www/.ruby/gems/1.8:/var/lib/gems/1.8/'
-every 1.minute do # Many shortcuts available: :hour, :day, :month, :year, :reboot
+every 1.hour do # Many shortcuts available: :hour, :day, :month, :year, :reboot
rake "validates_captcha:create_static_images COUNT=50"
end
every 1.day, :at => '1:30 am' do
rake "webpraca:jobs:remove_old"
rake "sitemap:refresh"
end
\ No newline at end of file
|
macbury/webpraca
|
0c16f278255d0a163bc9ecc7be18a79049dca6eb
|
Gem path in cron
|
diff --git a/config/schedule.rb b/config/schedule.rb
index b6e2af9..d8a28fc 100644
--- a/config/schedule.rb
+++ b/config/schedule.rb
@@ -1,12 +1,12 @@
set :environment, "production"
set :output, '/home/webpraca/www/apps/webpraca/shared/log/cron.log'
-env, :GEM_PATH, '/home/webpraca/www/.ruby/gems/1.8:/var/lib/gems/1.8/'
+env :GEM_PATH, '/home/webpraca/www/.ruby/gems/1.8:/var/lib/gems/1.8/'
every 1.minute do # Many shortcuts available: :hour, :day, :month, :year, :reboot
rake "validates_captcha:create_static_images COUNT=50"
end
every 1.day, :at => '1:30 am' do
rake "webpraca:jobs:remove_old"
rake "sitemap:refresh"
end
\ No newline at end of file
|
macbury/webpraca
|
cd22b6f62729a399c994ec6326c46d0c7bfc5154
|
Gem path
|
diff --git a/config/schedule.rb b/config/schedule.rb
index 4971c37..b6e2af9 100644
--- a/config/schedule.rb
+++ b/config/schedule.rb
@@ -1,11 +1,12 @@
set :environment, "production"
set :output, '/home/webpraca/www/apps/webpraca/shared/log/cron.log'
-set :GEM_PATH, '/home/webpraca/www/.ruby/gems/1.8:/var/lib/gems/1.8/'
+env, :GEM_PATH, '/home/webpraca/www/.ruby/gems/1.8:/var/lib/gems/1.8/'
+
every 1.minute do # Many shortcuts available: :hour, :day, :month, :year, :reboot
rake "validates_captcha:create_static_images COUNT=50"
end
every 1.day, :at => '1:30 am' do
rake "webpraca:jobs:remove_old"
rake "sitemap:refresh"
end
\ No newline at end of file
|
macbury/webpraca
|
42bd6d5378823af87b6025c70f88cd16c6937d1f
|
Gem path
|
diff --git a/config/schedule.rb b/config/schedule.rb
index 5dfb55c..4971c37 100644
--- a/config/schedule.rb
+++ b/config/schedule.rb
@@ -1,12 +1,11 @@
set :environment, "production"
set :output, '/home/webpraca/www/apps/webpraca/shared/log/cron.log'
-set :gem_path, '/home/webpraca/www/.ruby/gems/1.8:/usr/lib/ruby/gems/1.8'
-
+set :GEM_PATH, '/home/webpraca/www/.ruby/gems/1.8:/var/lib/gems/1.8/'
every 1.minute do # Many shortcuts available: :hour, :day, :month, :year, :reboot
rake "validates_captcha:create_static_images COUNT=50"
end
every 1.day, :at => '1:30 am' do
rake "webpraca:jobs:remove_old"
rake "sitemap:refresh"
end
\ No newline at end of file
|
macbury/webpraca
|
63f3a38e820143a873e4fc74cdad57c5bcc26903
|
Add gem_path to cron
|
diff --git a/config/schedule.rb b/config/schedule.rb
index 2cf11b3..5dfb55c 100644
--- a/config/schedule.rb
+++ b/config/schedule.rb
@@ -1,12 +1,12 @@
set :environment, "production"
set :output, '/home/webpraca/www/apps/webpraca/shared/log/cron.log'
-set :path, '/home/webpraca/www/apps/webpraca/current/'
+set :gem_path, '/home/webpraca/www/.ruby/gems/1.8:/usr/lib/ruby/gems/1.8'
every 1.minute do # Many shortcuts available: :hour, :day, :month, :year, :reboot
rake "validates_captcha:create_static_images COUNT=50"
end
every 1.day, :at => '1:30 am' do
rake "webpraca:jobs:remove_old"
rake "sitemap:refresh"
end
\ No newline at end of file
|
macbury/webpraca
|
06222b98b9fc1aa317a7b311ac4832ec706d7f7e
|
Remove patch
|
diff --git a/config/schedule.rb b/config/schedule.rb
index eb16f35..620eec3 100644
--- a/config/schedule.rb
+++ b/config/schedule.rb
@@ -1,14 +1,11 @@
set :environment, "production"
set :output, '/home/webpraca/www/apps/webpraca/shared/log/cron.log'
every 1.hour do # Many shortcuts available: :hour, :day, :month, :year, :reboot
rake "validates_captcha:create_static_images COUNT=50"
end
-shared_path = "/home/webpraca/www/apps/webpraca/shared"
-current_path = "/home/webpraca/www/apps/webpraca/current"
-
every 1.day, :at => '1:30 am' do
rake "webpraca:jobs:remove_old"
rake "sitemap:refresh"
end
\ No newline at end of file
|
macbury/webpraca
|
0050d37ac33cde1e767149d9f9d93e8b01ba5b18
|
Sitemap
|
diff --git a/config/schedule.rb b/config/schedule.rb
index 6d024b6..eb16f35 100644
--- a/config/schedule.rb
+++ b/config/schedule.rb
@@ -1,9 +1,14 @@
set :environment, "production"
-every :hour do # Many shortcuts available: :hour, :day, :month, :year, :reboot
+set :output, '/home/webpraca/www/apps/webpraca/shared/log/cron.log'
+
+every 1.hour do # Many shortcuts available: :hour, :day, :month, :year, :reboot
rake "validates_captcha:create_static_images COUNT=50"
end
+shared_path = "/home/webpraca/www/apps/webpraca/shared"
+current_path = "/home/webpraca/www/apps/webpraca/current"
+
every 1.day, :at => '1:30 am' do
- rake "sitemap:refresh"
rake "webpraca:jobs:remove_old"
+ rake "sitemap:refresh"
end
\ No newline at end of file
|
macbury/webpraca
|
fe2989956e2fafec4f077c4acbb6e2bf5e6d8af6
|
Active scope fix
|
diff --git a/app/controllers/jobs_controller.rb b/app/controllers/jobs_controller.rb
index fe22f7a..27aa352 100644
--- a/app/controllers/jobs_controller.rb
+++ b/app/controllers/jobs_controller.rb
@@ -1,173 +1,171 @@
class JobsController < ApplicationController
validates_captcha :only => [:create, :new]
ads_pos :bottom
ads_pos :right, :except => [:home, :index, :search]
ads_pos :none, :only => [:home]
def home
@page_title = ['najpopularniejsze oferty', 'najnowsze oferty']
query = Job.active.search
@recent_jobs = query.all(:order => "created_at DESC", :limit => 10, :include => [:localization, :category])
@top_jobs = query.all(:order => "rank DESC, created_at DESC", :limit => 10, :include => [:localization, :category])
end
# GET /jobs
# GET /jobs.xml
def index
- @query = Job.search
+ @query = Job.active.search
options = {
:page => params[:page],
:per_page => 25,
:order => "created_at DESC, rank DESC",
:include => [:localization, :category]
}
- @query.active
-
if params[:order] =~ /najpopularniejsze/i
@page_title = ['Najpopularniejsze oferty pracy']
@order = :rank
options[:order] = "rank DESC, created_at DESC"
else
@order = :created_at
@page_title = ['Najnowsze oferty pracy']
options[:order] = "created_at DESC, rank DESC"
end
if params[:category]
@category = Category.find_by_permalink!(params[:category])
@page_title << @category.name
@query.category_id_is(@category.id)
end
if params[:localization]
@localization = Localization.find_by_permalink!(params[:localization])
@page_title << @localization.name
@query.localization_id_is(@localization.id)
end
if params[:framework]
@framework = Framework.find_by_permalink!(params[:framework])
@page_title << @framework.name
options[:include] << :framework
@query.framework_id_is(@framework.id)
end
if params[:type_id]
@type_id = JOB_LABELS.index(params[:type_id]) || 0
@page_title << JOB_LABELS[@type_id]
@query.type_id_is(@type_id)
end
@jobs = @query.paginate(options)
respond_to do |format|
format.html # index.html.erb
format.rss
format.atom
end
end
def search
@page_title = ["Szukaj oferty"]
@search = Job.active.search(params[:search])
if params[:search]
@page_title = ["Znalezione oferty"]
@jobs = @search.paginate( :page => params[:page],
:per_page => 30,
:order => "created_at DESC, rank DESC" )
end
respond_to do |format|
format.html
format.rss { render :action => "index" }
format.atom { render :action => "index" }
end
end
# GET /jobs/1
# GET /jobs/1.xml
def show
@job = Job.find_by_permalink!(params[:id])
@job.visited_by(request.remote_ip)
@category = @job.category
respond_to do |format|
format.html # show.html.erb
end
end
# GET /jobs/new
# GET /jobs/new.xml
def new
@job = Job.new
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @job }
end
end
# POST /jobs
# POST /jobs.xml
def create
@job = Job.new(params[:job])
respond_to do |format|
if @job.save
flash[:notice] = 'Na twój e-mail zostaÅ wysÅany link którym opublikujesz ofertÄ.'
format.html { redirect_to(@job) }
format.xml { render :xml => @job, :status => :created, :location => @job }
else
format.html { render :action => "new" }
format.xml { render :xml => @job.errors, :status => :unprocessable_entity }
end
end
end
# GET /jobs/1/edit
def edit
@job = Job.find_by_permalink_and_token!(params[:id], params[:token])
render :action => "new"
end
# PUT /jobs/1
# PUT /jobs/1.xml
def update
@job = Job.find_by_permalink_and_token!(params[:id], params[:token])
respond_to do |format|
if @job.update_attributes(params[:job])
flash[:notice] = 'Zapisano zmiany w ofercie.'
format.html { redirect_to(@job) }
format.xml { head :ok }
else
format.html { render :action => "new" }
format.xml { render :xml => @job.errors, :status => :unprocessable_entity }
end
end
end
def publish
@job = Job.find_by_permalink_and_token!(params[:id], params[:token])
unless @job.published
@job.publish!
flash[:notice] = "Twoja oferta jest już widoczna!"
end
redirect_to @job
end
# DELETE /jobs/1
# DELETE /jobs/1.xml
def destroy
@job = Job.find_by_permalink_and_token!(params[:id], params[:token])
@job.destroy
flash[:notice] = "Oferta zostaÅa usuniÄta"
respond_to do |format|
format.html { redirect_to(jobs_url) }
format.xml { head :ok }
end
end
end
diff --git a/config/environment.rb b/config/environment.rb
index c46634e..c6ea631 100644
--- a/config/environment.rb
+++ b/config/environment.rb
@@ -1,49 +1,49 @@
# Be sure to restart your server when you modify this file
# Specifies gem version of Rails to use when vendor/rails is not present
# Bootstrap the Rails environment, frameworks, and default configuration
require File.join(File.dirname(__FILE__), 'boot')
Rails::Initializer.run do |config|
config.gem 'sitemap_generator', :lib => false, :source => 'http://gemcutter.org'
config.gem 'less', :source => 'http://gemcutter.org', :lib => false
config.gem 'meta-tags', :lib => 'meta_tags', :source => 'http://gemcutter.org'
config.gem 'declarative_authorization'
config.gem 'searchlogic'
config.gem 'RedCloth', :lib => "redcloth"
config.gem 'authlogic'
- #config.gem "newrelic_rpm"
+ config.gem "newrelic_rpm"
config.gem 'whenever', :lib => false, :source => 'http://gemcutter.org/'
config.gem 'highline', :lib => false
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Add additional load paths for your own custom dirs
# config.load_paths += %W( #{RAILS_ROOT}/extras )
# Specify gems that this application depends on and have them installed with rake gems:install
# config.gem "bj"
# config.gem "hpricot", :version => '0.6', :source => "http://code.whytheluckystiff.net"
# config.gem "sqlite3-ruby", :lib => "sqlite3"
# config.gem "aws-s3", :lib => "aws/s3"
# Only load the plugins named here, in the order given (default is alphabetical).
# :all can be used as a placeholder for all plugins not explicitly named
#config.plugins = [ :all, :less, 'less-rails' ]
# Skip frameworks you're not going to use. To use Rails without a database,
# you must remove the Active Record framework.
# config.frameworks -= [ :active_record, :active_resource, :action_mailer ]
# Activate observers that should always be running
# config.active_record.observers = :cacher, :garbage_collector, :forum_observer
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names.
config.time_zone = 'Warsaw'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}')]
config.i18n.default_locale = :pl
end
\ No newline at end of file
|
macbury/webpraca
|
92c334c63f9d8b956cf44322973a47b99e1bb3b2
|
Enable e-mails
|
diff --git a/app/models/job.rb b/app/models/job.rb
index c758f81..555d2c5 100644
--- a/app/models/job.rb
+++ b/app/models/job.rb
@@ -1,176 +1,176 @@
JOB_TYPES = ["zlecenie (konkretna usÅuga do wykonania)", "poszukiwanie wspóÅpracowników / oferta pracy", "wolontariat (praca za reklamy, bannery, itp. lub praca za darmo)", "staż/praktyka"]
JOB_LABELS = ["zlecenie", "etat", "wolontariat", "praktyka"]
JOB_ETAT = 1;
JOB_RANK_VALUES = {
:default => 0.3,
:price => 0.8,
:krs => 0.6,
:nip => 0.5,
:regon => 0.6,
:framework_id => 0.7,
:website => 0.3,
:apply_online => 0.2
}
class Job < ActiveRecord::Base
include ActionController::UrlWriter
xss_terminate
has_permalink :title
named_scope :active, :conditions => ["((jobs.end_at >= ?) AND (jobs.published = ?))", Date.current, true]
named_scope :old, :conditions => ["jobs.end_at < ?", Date.current]
named_scope :has_text, lambda { |text| { :conditions => ["((jobs.title ILIKE ?) OR (jobs.description ILIKE ?))", "%#{text}%", "%#{text}%"] } }
validates_presence_of :title, :description, :email, :company_name, :localization_id, :category_id
validates_length_of :title, :within => 3..255
validates_length_of :description, :within => 10..5000
validates_inclusion_of :type_id, :in => 0..JOB_TYPES.size-1
validates_inclusion_of :dlugosc_trwania, :in => 1..60
validates_numericality_of :price_from,
:greater_than => 0,
:unless => Proc.new { |j| j.price_from.nil? }
validates_numericality_of :price_to,
:greater_than => 0,
:unless => Proc.new { |j| j.price_to.nil? }
validates_format_of :email, :with => Authlogic::Regex.email
validates_format_of :website, :with => /(^$)|(^(http|https):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(([0-9]{1,5})?\/.*)?$)/ix
validates_format_of :regon,
:with => /(^$)|(^[0-9]{7,14}$)/
validates_format_of :nip,
:with => /(^$)|(^\d{2,3}-\d{2,3}-\d{2,3}-\d{2,3}$)/
validates_format_of :krs,
:with => /(^$)|(^\d{10})$/
belongs_to :framework
belongs_to :localization
belongs_to :category
has_many :applicants, :dependent => :delete_all
has_many :visits, :dependent => :delete_all
attr_protected :rank, :permalink, :end_at, :token, :published
attr_accessor :framework_name, :localization_name
before_create :create_from_name, :generate_token
before_save :calculate_rank
- #after_create :send_notification
+ after_create :send_notification
def self.find_grouped_by_type
return Job.active.count(:type_id, :group => "type_id")
end
def send_notification
JobMailer.deliver_job_posted(self)
end
def generate_token
alphanumerics = ('a'..'z').to_a.concat(('A'..'Z').to_a.concat(('0'..'9').to_a))
salt = alphanumerics.sort_by{rand}.to_s[0..1024]
self.token = Digest::SHA1.hexdigest("--#{salt}--#{self.id}--#{Date.current}--")
generate_token unless Job.find_by_token(self.token).nil?
end
def calculate_rank
self.rank = 1.0
self.rank += visits_count * 0.01 unless visits_count.nil?
[:regon, :nip, :krs, :framework_id, :website, :apply_online].each do |attribute|
val = send(attribute)
inc = JOB_RANK_VALUES[attribute] || JOB_RANK_VALUES[:default]
self.rank += inc unless (val.nil? || (val.class == String && val.empty?) || (val.class == TrueClass))
end
if widelki_zarobkowe?
self.rank += JOB_RANK_VALUES[:price]
price = price_from || price_to
if price >= 10_000 # ciekawe czy ktoÅ da tyle :P
self.rank += 0.8
elsif price >= 7000
self.rank += 0.7
elsif price >= 5000
self.rank += 0.6
elsif price >= 3000
self.rank += 0.3
elsif price < 2000
if self.type_id == JOB_ETAT
self.rank -= 0.6 # bo nikt za grosze nie chce pracowaÄ
else
self.rank += 0.3 # chyba że to biedny student
end
end
end
end
def widelki_zarobkowe?
((!self.price_from.nil? && self.price_from > 0) || (!self.price_to.nil? && self.price_to > 0))
end
def create_from_name
unless (self.framework_name.nil? || self.framework_name.blank?)
framework = Framework.name_like(self.framework_name).first
framework = Framework.create(:name => self.framework_name) if framework.nil?
self.framework = framework
end
unless (self.localization_name.nil? || self.localization_name.blank?)
localization = Localization.name_like(self.localization_name).first
localization = Localization.create(:name => self.localization_name) if localization.nil?
self.localization = localization
end
end
def dlugosc_trwania
date = created_at.nil? ? Date.current.to_date : created_at.to_date
return (read_attribute(:end_at) - date).to_i rescue 14
end
def dlugosc_trwania=(val)
date = created_at.nil? ? Date.current.to_date : created_at.to_date
write_attribute(:end_at, date+val.to_i.days)
end
def highlited?
self.rank >= 4.75
end
def publish!
self.published = true
save
spawn do
tags = [localization.name, category.name]
tags << framework.name unless framework.nil?
MicroFeed.send :streams => :all,
:msg => "[#{company_name}] - #{title}",
:tags => tags,
:link => seo_job_url(job, :host => "webpraca.net")
end
end
def visited_by(ip)
visit = visits.find_or_create_by_ip(IPAddr.new(ip).to_i)
visits_count += 1 if visit.new_record?
save
end
def to_param
permalink
end
end
|
macbury/webpraca
|
c33457e9ce10cc2001f6d70630ce4f4cb2bc9d19
|
Job email applicant title
|
diff --git a/app/models/job_mailer.rb b/app/models/job_mailer.rb
index 3498ea7..5dcc25b 100644
--- a/app/models/job_mailer.rb
+++ b/app/models/job_mailer.rb
@@ -1,33 +1,37 @@
class JobMailer < ActionMailer::Base
include ActionController::UrlWriter
def job_applicant(applicant)
setup_email(applicant.job.email)
- @subject = "webpraca.net - PojawiÅa siÄ osoba zainteresowana ofertÄ
'#{applicant.job.title}'"
+ if applicant.job.email_title.nil? || applicant.job.email_title.empty?
+ @subject = "webpraca.net - PojawiÅa siÄ osoba zainteresowana ofertÄ
'#{applicant.job.title}'"
+ else
+ @subject = applicant.job.email_title
+ end
@body[:job] = applicant.job
@body[:applicant] = applicant
@body[:job_path] = seo_job_url(applicant.job)
@body[:attachment_path] = download_job_applicant_url(applicant.job, applicant.token) if applicant.have_attachment?
end
def job_posted(job)
setup_email(job.email)
@subject = "webpraca.net - Twoja oferta zostaÅa dodana"
@body[:job] = job
@body[:job_path] = seo_job_url(job)
@body[:publish_path] = publish_job_url(job, :token => job.token)
@body[:edit_path] = edit_job_url(job, :token => job.token)
@body[:destroy_path] = destroy_job_url(job, :token => job.token)
end
protected
def setup_email(email)
@recipients = email
#@subject = "[mycode] "
@sent_on = Time.now
@from = ActionMailer::Base.smtp_settings[:from]
default_url_options[:host] = "webpraca.net"
end
end
diff --git a/app/views/jobs/_form.html.erb b/app/views/jobs/_form.html.erb
index a1a62ae..ae6bbb4 100644
--- a/app/views/jobs/_form.html.erb
+++ b/app/views/jobs/_form.html.erb
@@ -1,55 +1,59 @@
<%= hidden_field_tag 'token', params[:token] unless params[:token].nil? %>
<% form.inputs :name => 'SzczegóÅy oferty pracy' do %>
<%= form.input :title %>
<%= form.input :category_id, :as => :select, :collection => Category.all.map { |c| [c.name, c.id] } %>
<li class="select">
<%= form.label :localization_id, 'Lokalizacja*' %>
<%= form.select :localization_id, Localization.all(:order => 'name').map { |localization| [localization.name, localization.id] } %> albo
<%= form.text_field :localization_name %>
<p class="inline-hints">np. 'Warszawa', 'Kraków, UK'</p>
<%= inline_errors @job, :localization_name %>
</li>
<%= form.input :type_id, :as => :radio, :collection => collection_from_types(JOB_TYPES) %>
<%= form.input :remote_job, :required => false %>
- <%= form.input :apply_online, :required => false, :hint => "uaktywnia formularz umożliwiajÄ
cy przesyÅanie aplikacji online w ofercie" %>
<%= form.input :dlugosc_trwania, :as => :numeric, :hint => "ile dni oferta ma byÄ ważna(od 1 do 60 dni)" %>
<li class="select">
<%= form.label :framework_id, 'Framework' %>
<%= form.select :framework_id, Framework.all(:order => 'name').map { |frame| [frame.name, frame.id] }, :include_blank => true %> albo
<%= form.text_field :framework_name %>
<p class="inline-hints">gÅówny framework którego znajomoÅÄ jest wymagana, podaj peÅnÄ
nazwÄ</p>
<%= inline_errors @job, :framework_name %>
</li>
<li class="numeric prices">
<label>WideÅki zarobkowe:</label>
<%= form.text_field :price_from %> do <%= form.text_field :price_to %> PLN na miesiÄ
c, netto
<%= inline_errors @job, :price_from %>
<%= inline_errors @job, :price_to %>
</li>
<li>
<%= form.label :description, 'Opis*' %>
<%= form.text_area :description %>
<%= inline_errors @job, :description %>
</li>
<% end %>
+<% form.inputs :name => "Aplikuj online" do %>
+ <%= form.input :apply_online, :required => false, :hint => "uaktywnia formularz umożliwiajÄ
cy przesyÅanie aplikacji online w ofercie" %>
+ <%= form.input :email_title, :required => false, :hint => "np. MÅodszy programista, Ruby Developer/18/12/71 itp" %>
+<% end %>
+
<% form.inputs :name => 'Firma zatrudniajÄ
ca lub osoba zlecajÄ
ca' do %>
<%= form.input :email, :hint => "Pod wskazany adres zostanÄ
przesÅane linki do edycji oferty, nie bÄdzie on widoczny publicznie(zamiast niego bÄdzie dostÄpny formularz kontaktowy)." %>
<%= form.input :company_name %>
<%= form.input :website, :hint => "zaczynajÄ
cy siÄ od http://", :required => false %>
<%= form.input :nip, :required => false %>
<%= form.input :regon, :required => false %>
<%= form.input :krs, :required => false %>
<% end %>
<% if @job.new_record? %>
<% form.inputs :name => "Czy jesteÅ czÅowiekiem" do %>
<li class="string required">
<%= form.label :captcha, 'Kod z obrazka*' %>
<%= form.captcha_challenge %>
<%= form.captcha_field %>
<%= inline_errors @job, :captcha_solution %>
</li>
<% end %>
<% end %>
\ No newline at end of file
diff --git a/config/environment.rb b/config/environment.rb
index c6ea631..c46634e 100644
--- a/config/environment.rb
+++ b/config/environment.rb
@@ -1,49 +1,49 @@
# Be sure to restart your server when you modify this file
# Specifies gem version of Rails to use when vendor/rails is not present
# Bootstrap the Rails environment, frameworks, and default configuration
require File.join(File.dirname(__FILE__), 'boot')
Rails::Initializer.run do |config|
config.gem 'sitemap_generator', :lib => false, :source => 'http://gemcutter.org'
config.gem 'less', :source => 'http://gemcutter.org', :lib => false
config.gem 'meta-tags', :lib => 'meta_tags', :source => 'http://gemcutter.org'
config.gem 'declarative_authorization'
config.gem 'searchlogic'
config.gem 'RedCloth', :lib => "redcloth"
config.gem 'authlogic'
- config.gem "newrelic_rpm"
+ #config.gem "newrelic_rpm"
config.gem 'whenever', :lib => false, :source => 'http://gemcutter.org/'
config.gem 'highline', :lib => false
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Add additional load paths for your own custom dirs
# config.load_paths += %W( #{RAILS_ROOT}/extras )
# Specify gems that this application depends on and have them installed with rake gems:install
# config.gem "bj"
# config.gem "hpricot", :version => '0.6', :source => "http://code.whytheluckystiff.net"
# config.gem "sqlite3-ruby", :lib => "sqlite3"
# config.gem "aws-s3", :lib => "aws/s3"
# Only load the plugins named here, in the order given (default is alphabetical).
# :all can be used as a placeholder for all plugins not explicitly named
#config.plugins = [ :all, :less, 'less-rails' ]
# Skip frameworks you're not going to use. To use Rails without a database,
# you must remove the Active Record framework.
# config.frameworks -= [ :active_record, :active_resource, :action_mailer ]
# Activate observers that should always be running
# config.active_record.observers = :cacher, :garbage_collector, :forum_observer
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names.
config.time_zone = 'Warsaw'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}')]
config.i18n.default_locale = :pl
end
\ No newline at end of file
diff --git a/config/locales/pl.yml b/config/locales/pl.yml
index 4c0ed03..1843146 100644
--- a/config/locales/pl.yml
+++ b/config/locales/pl.yml
@@ -1,174 +1,175 @@
# Polish translations for Ruby on Rails
# by Jacek Becela (jacek.becela@gmail.com, http://github.com/ncr)
pl:
number:
format:
separator: ","
delimiter: " "
precision: 2
currency:
format:
format: "%n %u"
unit: "PLN"
percentage:
format:
delimiter: ""
precision:
format:
delimiter: ""
human:
format:
delimiter: ""
precision: 1
storage_units:
format: "%n %u"
units:
byte:
one: "bajt"
other: "bajty"
kb: "KB"
mb: "MB"
gb: "GB"
tb: "TB"
date:
formats:
default: "%Y-%m-%d"
short: "%d %b"
school: "%Y"
simple: "%d.%m.%Y"
long: "%d %B %Y"
day_names: [Niedziela, PoniedziaÅek, Wtorek, Åroda, Czwartek, PiÄ
tek, Sobota]
abbr_day_names: [nie, pon, wto, Åro, czw, pia, sob]
month_names: [~, StyczeÅ, Luty, Marzec, KwiecieÅ, Maj, Czerwiec, Lipiec, SierpieÅ, WrzesieÅ, Październik, Listopad, GrudzieÅ]
abbr_month_names: [~, sty, lut, mar, kwi, maj, cze, lip, sie, wrz, paź, lis, gru]
order: [ :year, :month, :day ]
time:
formats:
default: "%a, %d %b %Y, %H:%M:%S %z"
short: "%d %b, %H:%M"
long: "%d %B %Y, %H:%M"
am: "przed poÅudniem"
pm: "po poÅudniu"
datetime:
distance_in_words:
half_a_minute: "póŠminuty"
less_than_x_seconds:
one: "mniej niż sekundÄ"
few: "mniej niż {{count}} sekundy"
other: "mniej niż {{count}} sekund"
x_seconds:
one: "sekundÄ"
few: "{{count}} sekundy"
other: "{{count}} sekund"
less_than_x_minutes:
one: "mniej niż minutÄ"
few: "mniej niż {{count}} minuty"
other: "mniej niż {{count}} minut"
x_minutes:
one: "minutÄ"
few: "{{count}} minuty"
other: "{{count}} minut"
about_x_hours:
one: "okoÅo godziny"
other: "okoÅo {{count}} godzin"
x_days:
one: "1 dzieÅ"
other: "{{count}} dni"
about_x_months:
one: "okoÅo miesiÄ
ca"
other: "okoÅo {{count}} miesiÄcy"
x_months:
one: "1 miesiÄ
c"
few: "{{count}} miesiÄ
ce"
other: "{{count}} miesiÄcy"
about_x_years:
one: "okoÅo roku"
other: "okoÅo {{count}} lat"
over_x_years:
one: "ponad rok"
few: "ponad {{count}} lata"
other: "ponad {{count}} lat"
activerecord:
models:
user: "Użytkownik"
job: "Praca"
search: "Wyszukiwarka"
applicant: "Aplikant"
comment:
attributes:
captcha_solution:
blank: 'musi byÄ podane'
invalid: 'odpowiedź jest niepoprawna'
attributes:
websiteconfig:
groups:
website: "Strona WWW"
js: "Skrypty"
js:
google_analytics: "Google Analytics"
widget: "Reklama"
website:
name: "Nazwa"
tags: "SÅowa kluczowe"
description: "Opis"
applicant:
email: "Twój E-Mail"
body: "TreÅÄ"
cv: "Dodaj ofertÄ/CV"
job:
title: "TytuÅ"
place_id: "Lokalizacja"
description: "Opis"
dlugosc_trwania: "DÅugoÅÄ trwania"
remote_job: "Praca zdalna"
type_id: "Typ"
category_id: "Kategoria"
company_name: "Nazwa"
website: "Strona WWW"
framework_name: "Framework"
apply_online: "Aplikuj online"
+ email_title: "TytuÅ emaila"
user:
password: "HasÅo"
password_confirmation: "Powtórz hasÅo"
errors:
template:
header:
one: "{{model}} nie zostaÅ zachowany z powodu jednego bÅÄdu"
other: "{{model}} nie zostaÅ zachowany z powodu {{count}} bÅÄdów"
body: "BÅÄdy dotyczÄ
nastÄpujÄ
cych pól:"
messages:
inclusion: "nie znajduje siÄ na liÅcie dopuszczalnych wartoÅci"
exclusion: "znajduje siÄ na liÅcie zabronionych wartoÅci"
invalid: "jest nieprawidÅowe"
confirmation: "nie zgadza siÄ z potwierdzeniem"
accepted: "musi byÄ zaakceptowane"
empty: "nie może byÄ puste"
blank: "nie może byÄ puste"
too_long: "jest za dÅugie (maksymalnie {{count}} znaków)"
too_short: "jest za krótkie (minimalnie {{count}} znaków)"
wrong_length: "jest nieprawidÅowej dÅugoÅci (powinna wynosiÄ {{count}} znaków)"
taken: "zostaÅo już zajÄte"
not_a_number: "nie jest liczbÄ
"
greater_than: "musi byÄ wiÄksze niż {{count}}"
greater_than_or_equal_to: "musi byÄ wiÄksze lub równe {{count}}"
equal_to: "musi byÄ równe {{count}}"
less_than: "musi byÄ mniejsze niż {{count}}"
less_than_or_equal_to: "musi byÄ mniejsze lub równe {{count}}"
odd: "musi byÄ nieparzyste"
even: "musi byÄ parzyste"
record_invalid: "nieprawidÅowe dane"
support:
array:
sentence_connector: "i"
skip_last_comma: true
words_connector: ", "
two_words_connector: " i "
last_word_connector: " oraz "
diff --git a/db/migrate/20100105185950_add_email_title_to_jobs.rb b/db/migrate/20100105185950_add_email_title_to_jobs.rb
new file mode 100644
index 0000000..cc12b85
--- /dev/null
+++ b/db/migrate/20100105185950_add_email_title_to_jobs.rb
@@ -0,0 +1,9 @@
+class AddEmailTitleToJobs < ActiveRecord::Migration
+ def self.up
+ add_column :jobs, :email_title, :string
+ end
+
+ def self.down
+ remove_column :jobs, :email_title
+ end
+end
diff --git a/db/schema.rb b/db/schema.rb
index 88895c8..3aae89d 100644
--- a/db/schema.rb
+++ b/db/schema.rb
@@ -1,132 +1,133 @@
# This file is auto-generated from the current state of the database. Instead of editing this file,
# please use the migrations feature of Active Record to incrementally modify your database, and
# then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your database schema. If you need
# to create the application database on another system, you should be using db:schema:load, not running
# all the migrations from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended to check this file into your version control system.
-ActiveRecord::Schema.define(:version => 20100103183928) do
+ActiveRecord::Schema.define(:version => 20100105185950) do
create_table "applicants", :force => true do |t|
t.string "email"
t.text "body"
t.integer "job_id"
t.datetime "created_at"
t.datetime "updated_at"
t.string "cv_file_name"
t.string "cv_content_type"
t.integer "cv_file_size"
t.datetime "cv_updated_at"
t.string "token"
end
create_table "assignments", :force => true do |t|
t.integer "user_id"
t.integer "role_id"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "brain_busters", :force => true do |t|
t.string "question"
t.string "answer"
end
create_table "categories", :force => true do |t|
t.string "name"
t.string "permalink"
t.integer "position", :default => 0
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "frameworks", :force => true do |t|
t.string "name"
t.string "permalink"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "jobs", :force => true do |t|
t.integer "type_id", :default => 0
t.integer "price_from"
t.integer "price_to"
t.boolean "remote_job"
t.string "title"
t.string "permalink"
t.text "description"
t.date "end_at"
t.string "company_name"
t.string "website"
t.integer "localization_id"
t.string "nip"
t.string "regon"
t.string "krs"
t.string "email"
t.datetime "created_at"
t.datetime "updated_at"
t.integer "framework_id"
t.float "rank"
t.string "token"
t.boolean "published"
t.integer "visits_count", :default => 0
t.boolean "apply_online", :default => true
t.integer "applicants_count", :default => 0
t.integer "category_id"
+ t.string "email_title"
end
create_table "localizations", :force => true do |t|
t.string "name"
t.string "permalink"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "pages", :force => true do |t|
t.string "name"
t.string "permalink"
t.text "body"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "roles", :force => true do |t|
t.string "name"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "users", :force => true do |t|
t.string "login"
t.string "email", :null => false
t.string "crypted_password", :null => false
t.string "password_salt", :null => false
t.string "persistence_token", :null => false
t.integer "login_count", :default => 0, :null => false
t.datetime "last_request_at"
t.datetime "last_login_at"
t.datetime "current_login_at"
t.string "last_login_ip"
t.string "current_login_ip"
t.datetime "created_at"
t.datetime "updated_at"
t.integer "visits_count", :default => 0
end
add_index "users", ["email"], :name => "index_users_on_email"
add_index "users", ["last_request_at"], :name => "index_users_on_last_request_at"
add_index "users", ["login"], :name => "index_users_on_login"
add_index "users", ["persistence_token"], :name => "index_users_on_persistence_token"
create_table "visits", :force => true do |t|
t.integer "job_id"
t.datetime "created_at"
t.datetime "updated_at"
t.integer "ip", :limit => 8
end
end
|
macbury/webpraca
|
7eaac8a6768db82edadc905bd144586e4f3cc26f
|
CSS fix for show action
|
diff --git a/app/stylesheets/ui.less b/app/stylesheets/ui.less
index a39f3fb..f4da3d9 100644
--- a/app/stylesheets/ui.less
+++ b/app/stylesheets/ui.less
@@ -1,602 +1,602 @@
/* Defaults */
@text_color: #393733;
@link_color: #31627E;
@hover_color: #FF5917;
/* Global */
body {
margin: 0;
padding: 0;
font: 12px Arial;
color: @text_color;
overflow: auto;
background: #76787B url('/images/bkg.png') repeat-x top;
}
h1, h2, h3, h4 { margin: 0 0 5px 0; }
a { color: @link_color; cursor: pointer; outline: none !important; text-decoration: none; }
a:hover, a:focus { color: @hover_color; }
a img { border: 0; }
/* Table */
table { border-collapse: collapse; width: 100%; }
td, th {
font-size:11px;
border-bottom:1px solid #eee;
padding:5px;
}
th { text-align:left; font-size:12px; }
thead th { font-weight:bold; color:#666; padding:2px 5px; font-size:11px; background:#e1e1e1 url(/images/nav-bg.gif) top left repeat-x; border-left:1px solid #ddd; border-bottom:1px solid #ddd; }
thead th:first-child { border-left:none !important; }
thead th.optional { font-weight:normal !important; }
tr.alt { background:#f6f6f6; }
/* IDS */
.prices input[type="text"] { width: 50px !important; text-align: right; }
#job_captcha_image, #applicant_captcha_image, .captcha img { margin-bottom: -22px !important; margin-right: 10px !important; }
#job_captcha_solution, #applicant_captcha_solution, .captcha input { width: 200px !important; }
#AdTaily_Widget_Container { padding-top: 5px; }
/* Custom class */
.rounded_corners (@radius: 5px) {
-moz-border-radius: @radius;
-webkit-border-radius: @radius;
border-radius: @radius;
-o-border-radius: @radius;
}
.rounded_corner_top_left(@radius: 5px) { -moz-border-radius-topleft: @radius; -webkit-border-top-left-radius: @radius; border-top-left-radius: @radius; }
.rounded_corner_top_right(@radius: 5px) { -moz-border-radius-topright: @radius; -webkit-border-top-right-radius: @radius; border-top-right-radius: @radius; }
.rounded_corner_bottom_left(@radius: 5px) { -moz-border-radius-bottomleft: @radius; -webkit-border-bottom-left-radius: @radius; border-bottom-left-radius: @radius; }
.rounded_corner_bottom_right(@radius: 5px) { -moz-border-radius-bottomright: @radius; -webkit-border-bottom-right-radius: @radius; border-bottom-right-radius: @radius; }
.reset { margin: 0; padding: 0; list-style: none; }
.text_center { text-align: center; }
.text_right { text-align: right; }
.clear { clear: both; }
.info { text-align: center; color: #ddd; font-size: 28px; font-weight: bold; }
.loader { background: transparent url('/images/ajax.gif') no-repeat center center; height: 20px; display: none; }
.right { float: right; }
.left { float: left; }
/* Flash */
.flash {
background-color: #A4E1A2;
border: 1px solid #DDE3D7;
text-shadow: #C0FDE3 0px 1px 0px;
.rounded_corners(5px);
color: #094808;
margin-top: 10px;
opacity: 0.8;
padding: 10px;
}
.flash.error {
background-color: #AF2B2B;
color: #fff;
border: 1px solid #DA3536;
text-shadow: #000 0px 1px 0px;
}
.flash:hover { opacity: 1.0; }
.flash .dismiss {
background: transparent url('/images/close.png') no-repeat !important;
float: right;
height: 10px;
width: 9px;
text-indent: 9999px;
overflow: hidden;
}
.flash p {
font-weight: normal;
line-height: 15px;
margin: 0px;
}
.flash_error {
background: #AF2B2B url('../images/icon-error.png') 20px center no-repeat;
color: #fff;
border: 1px solid #DA3536;
text-shadow: #000 0px 1px 0px;
}
/* Buttons */
.buttons { margin: 0 5px; }
.button {
background: #DDD url('../images/button.png') repeat-x 0px 0px;
border: 1px solid #999;
display: inline-block;
outline: none;
-webkit-box-shadow: rgba(0, 0, 0, 0.117188) 0px 1px 0px;
}
.button > input[type="button"], .button > input[type="submit"], .button > a {
border: none;
line-height: 23px;
height: 23px;
padding: 0 10px;
color: #333 !important;
font-weight: bold;
text-decoration: none;
font-size: 11px;
cursor: default;
background: transparent;
}
.button:active {
background-color: #ddd;
background-image: none;
}
.button img {
margin-bottom: -4px;
margin-right: 5px;
width: 16px;
height: 16px;
}
.button.right { float: right; }
/* TextFields */
select { min-width: 150px; }
input[type="text"], input[type="password"], textarea {
padding: 4px 3px !important;
border: 1px solid #96A6C5;
color: #000;
}
textarea { height: 200px; min-height: 200px; }
input[type="text"]:focus, input[type="password"]:focus, textarea:focus {
background-color: #e6f7ff;
border-bottom: 1px solid #7FAEFF;
border-right: 1px solid #7FAEFF;
border-left: 1px solid #4478A8;
border-top: 1px solid #4478A8;
}
form > fieldset {
border: 2px solid #ddd !important;
.rounded_corners;
padding: 10px 15px !important;
margin: 10px 5px !important;
}
form > fieldset > legend {
font-weight: bold;
padding: 0 15px 0px 0 !important;
margin-left: -22px !important;
background: #fff;
font-size: 16px;
color: #333 !important;
}
/* Wrapper */
@wrapper_width: 900px;
.wrapper {
margin: 0px auto;
width: @wrapper_width;
min-height: 500px;
}
/* Header */
@header_height: 80px;
.wrapper > .header {
height: @header_height;
width: @wrapper_width;
position:relative;
}
@logo_width: 347px;
@menu_color: #35373A;
@header_link_color: #D8D8D9;
.header > h1#logo {
left: 8px;
position: absolute;
top: 10px;
width: @logo_width;
}
.header > h1#logo a { color: #fff; font: 28px "Trebuchet MS"; font-weight: bold; }
.header > h1#logo a:hover { background: transparent; }
.header > ul.categories {
.reset;
position: absolute;
bottom: 5px;
left: 0px;
width: @content_width;
}
.header > ul.categories li {
display:inline;
margin-left: 3px;
}
.header > ul.categories li.right { float: right; margin-left: 6px; }
.header > ul.categories li > a {
padding: 5px 10px;
margin-top: 5px;
font-size: 13px;
color: @header_link_color;
.rounded_corner_top_left;
.rounded_corner_top_right;
background: @menu_color;
}
.header > ul.categories li > a:hover { background: #5d5f62; }
.header > ul.categories li > .selected { color: #fff; background: #2A2B2D !important; }
.header > ul.menu {
.reset;
.rounded_corner_bottom_left;
.rounded_corner_bottom_right;
position:absolute;
top: 0px;
padding: 5px 10px;
right: 0px;
background: @menu_color;
}
.header > ul.menu li{
display:inline;
margin-left: 3px;
padding-left: 6px;
border-left: 1px dotted #212326;
background-color:transparent;
font-size: 10px;
font-weight: bold;
color: @header_link_color;
}
.header > ul.menu li a { color: @header_link_color; }
.header > ul.menu li a:hover { color: #fff; background: transparent; }
.header > ul.menu li:first-child { border: 0; margin-left: 0; padding-left: 0; }
/* Sidebar */
@sidebar_width: 200px;
.wrapper > .sidebar {
float: right;
width: @sidebar_width;
margin-top: 20px;
}
.wrapper > .sidebar ul { .reset; }
/* content */
@content_padding_right: 10px;
@content_width: @wrapper_width - @sidebar_width - @content_padding_right;
.wrapper > .content {
float: left;
width: @content_width;
padding-right: @content_padding_right;
margin-top: 20px;
}
/*.wrapper > .content p { margin: 0 0 10px 0; padding: 0;} */
/* Box */
.box {
margin-bottom: 10px;
padding: 6px;
background: #9C9C9C;
.rounded_corners(5px);
}
@box_div_border_radius: 4px;
.box > div {
background: #fff;
margin-bottom: 10px;
padding-bottom: 5px;
.rounded_corners(@box_div_border_radius);
}
-.box > div > div { margin: 10px; }
-.box > div > div p { margin: 10px 0; }
+.box > div > .text { margin: 10px; }
+.box > div > .text p { margin: 10px 0; }
.box > div:last-child { margin-bottom: 0; }
@title_height: 39px;
@sidebar_title_height: 29px;
.box .title {
height: @title_height;
.rounded_corner_top_right(@box_div_border_radius);
.rounded_corner_top_left(@box_div_border_radius);
display: block;
background: #fff url('/images/title-header.png') repeat-x bottom;
border-bottom: 1px solid #F1EFBD;
}
.box .title > h2, .box .title > h3 {
margin: 0;
padding: 1px 10px 0 10px;
line-height: @title_height - 1px;
font-weight: normal;
font-size: 18px;
color: #656666;
}
.box .title > h3 {
font-size: 16px;
line-height: @sidebar_title_height - 1px;
}
.box .title > h2 > span, .box .title > h3 > span { color: #8E8F8F; }
.box > div form { margin: 5px !important; }
.box p {
margin: 10px;
}
.sidebar .box .title, .box .title.mini {
height: @sidebar_title_height;
}
/* list */
.list {
.reset;
.clear;
}
.list > li { clear: both; padding: 5px; }
.list > .alt { background:#f6f6f6; }
.list > li > .ranked { font-weight: bold; }
.list > li .handle { cursor: move; margin: 3px 5px 0 5px; }
.list > li > .badge {
float: right;
min-width: 18px;
padding: 2px 3px;
font-weight: bold;
font-size: 10px;
color: #fff;
background: #8798BB;
.rounded_corners(7px);
text-align: center;
}
.list > li > .rank {
.rounded_corners(2px);
text-align: center;
min-width: 18px;
padding: 2px 3px;
font-weight: bold;
font-size: 9px;
float: right;
background: #FFFF98;
border: 1px solid #E2E28C;
margin-top: -1px;
}
.list > li > .date {
font-size: 11px;
font-style: italic;
color: #7C7C7C;
}
/* more button */
.more {
background: #fff url('/images/more.gif') 0% 0% repeat-x;
border: 1px solid #DDD;
border-bottom: 1px solid #AAA;
border-right: 1px solid #AAA;
display: block;
font-size: 14px;
font-weight: bold;
color: inherit;
height: 22px;
line-height: 1.5em;
padding: 6px 0px;
text-align: center;
text-shadow: #fff 1px 1px 1px;
.rounded_corners(6px);
}
.more:hover {
background-position: 0% -78px;
border: 1px solid #BBB;
color: inherit;
}
.more:active {
background-position: 0% -38px;
color: #666;
}
/* Etykiety */
.etykieta {
display: block;
float: left;
font-size: 9px;
margin-right: 5px;
margin-top: -1px;
text-align: center;
width: 60px;
.rounded_corners(2px);
padding: 2px 3px;
color: #fff;
}
.etykieta:hover { color: #fff; }
.etykieta.zdalnie {
background: #357CCB;
border: 1px solid #2C6AB0;
}
.etykieta.zlecenie {
background: #F8854E;
border: 1px solid #D27244;
}
.etykieta.etat {
background: #408000;
border: 1px solid #366E01;
}
.etykieta.praktyka {
background: #FF6;
border: 1px solid #E2E25C;
color: #31627E;
}
.praktyka:hover { color: #31627E; }
.etykieta.wolontariat {
background: #D6D6D6;
border: 1px solid #B1B1B1;
color: #31627E;
}
.wolontariat:hover { color: #31627E; }
/* Pagination */
.pagination { background: white; margin: 5px 5px 0 5px; }
.pagination a, .pagination span {
padding: .2em .5em;
display: block;
float: left;
margin-right: 1px;
}
.pagination span.disabled {
color: #999;
border: 1px solid #DDD;
}
.pagination span.current {
font-weight: bold;
background: #2E6AB1;
color: white;
border: 1px solid #2E6AB1;
}
.pagination a {
text-decoration: none;
color: #105CB6;
border: 1px solid #9AAFE5;
}
.pagination a:hover, .pagination a:focus {
color: #003;
border-color: #003;
background-color: transparent;
}
.pagination .page_info {
background: #2E6AB1;
color: white;
padding: .4em .6em;
width: 22em;
margin-bottom: .3em;
text-align: center;
}
.pagination .page_info b {
color: #003;
background: #6aa6ed;
padding: .1em .25em;
}
.pagination:after {
content: ".";
display: block;
height: 0;
clear: both;
visibility: hidden;
}
* html .pagination { height: 1%; }
*:first-child+html .pagination { overflow: hidden; }
/* describe list */
@dt_width: 180px;
@dt_padding_right: 10px;
@dl_padding_left: 10px;
dl {
padding: 0px;
margin: 10px 0 0 0;
display: block;
}
dl dt {
width: @dt_width;
text-align: right;
color: #888;
float: left;
display: block;
padding: 0 @dt_padding_right 6px 0;
margin: 0;
}
dl dd {
width: @content_width - @dt_width - @dt_padding_right - @dl_padding_left - 15px;
border-left: 1px solid #ccc;
float: left;
padding: 0 0 10px @dl_padding_left;
margin: 0;
}
dl dd:last-child { padding-bottom: 0px; }
dl dd ul {
padding: 5px 0 0 20px;
margin: 0;
}
/* feed icon */
.feed {
float: right;
margin-top: 5px;
margin-right: -3px;
}
/* footer */
.footer {
margin: 10px auto;
width: @wrapper_width;
color: #D8D8D9;
}
.footer strong a { color: #fff; }
.footer a { color: #D8D8D9; }
.footer a:hover { color: #fff; }
.footer .right { margin-top: 3px; }
\ No newline at end of file
diff --git a/app/views/jobs/show.html.erb b/app/views/jobs/show.html.erb
index c83c146..01a6db5 100644
--- a/app/views/jobs/show.html.erb
+++ b/app/views/jobs/show.html.erb
@@ -1,84 +1,84 @@
<% title [@job.category.name, @job.localization.name, @job.company_name, @job.title] %>
<div class="box">
<div>
<div class="title">
<h2>
<%= @job.title %>
</h2>
</div>
<dl>
<dt>Typ</dt>
<dd><%= job_label(@job) %></dd>
<dt>Kategoria</dt>
<dd><%= link_to @job.category.name, job_category_path(@job.category) %></dd>
<dt>Ocena</dt>
<dd><%= format_rank(@job.rank) %></dd>
<dt>Pracodawca</dt>
<dd><%= link_to @job.company_name, @job.website, :target => "_blank" %></dd>
<dt>Lokalizacja</dt>
<dd><%= link_to @job.localization.name, localization_path(@job.localization) %></dd>
<% unless @job.framework.nil? %>
<dt>Framework</dt>
<dd><%= link_to @job.framework.name, framework_path(@job.framework) %></dd>
<% end %>
<% if @job.widelki_zarobkowe? %>
<dt>WideÅko zarobkowe</dt>
<dd>
<%= "od #{number_to_currency(@job.price_from)}" unless @job.price_from.nil? %>
<%= "do #{number_to_currency(@job.price_to)}" unless @job.price_to.nil? %> na miesiÄ
c, netto
</dd>
<% end %>
<% unless @job.apply_online %>
<dt>Kontakt</dt>
<dd><%= link_to "Formularz kontaktowy", contact_path(:job_id => @job.id) %></dd>
<% end %>
<% unless (@job.regon.nil? || @job.regon.empty?) %>
<dt>REGON</dt>
<dd><%= @job.regon %> </dd>
<% end %>
<% unless (@job.nip.nil? || @job.nip.empty?) %>
<dt>NIP</dt>
<dd><%= @job.nip %> </dd>
<% end %>
<% unless (@job.krs.nil? || @job.krs.empty?) %>
<dt>KRS</dt>
<dd><%= link_to @job.krs, "http://krs.ms.gov.pl/Podmiot.aspx?nrkrs=#{@job.krs}", :target => "_blank" %> </dd>
<% end %>
<dt>Data rozpoczÄcia</dt>
<dd>
<%= l @job.created_at, :format => :long %>
<br />
<abbr title="<%= @job.created_at.xmlschema %>"><%= distance_of_time_in_words_to_now @job.created_at %> temu</abbr>
</dd>
<dt>Data zakoÅczenia</dt>
<dd>
<%= l @job.end_at, :format => :long %>
<br />
za <abbr title="<%= @job.end_at.xmlschema %>"><%= distance_of_time_in_words_to_now(@job.end_at) %></abbr>
</dd>
<dt>WyÅwietlona</dt>
<dd><%= @job.visits_count %> razy</dd>
</dl>
<div class="clear"></div>
</div>
<div>
<div class="title mini">
<h3>Opis oferty</h3>
</div>
- <div>
+ <div class="text">
<%= RedCloth.new(@job.description).to_html %>
</div>
<p>
<% if permitted_to? :edit, @job %>
<%= link_to 'Edytuj', edit_job_path(@job) %> |
<%= link_to 'Wstecz', jobs_path %>
<% end %>
</p>
</div>
<%= link_to 'Aplikuj online!', new_job_applicant_path(@job), :class => "more" if @job.apply_online %>
</div>
|
macbury/webpraca
|
75d5a15f1ac26f4c7ed2091b1d60ff04c6335328
|
View fix
|
diff --git a/app/views/jobs/show.html.erb b/app/views/jobs/show.html.erb
index da928ec..c83c146 100644
--- a/app/views/jobs/show.html.erb
+++ b/app/views/jobs/show.html.erb
@@ -1,82 +1,84 @@
<% title [@job.category.name, @job.localization.name, @job.company_name, @job.title] %>
<div class="box">
<div>
<div class="title">
<h2>
<%= @job.title %>
</h2>
</div>
<dl>
<dt>Typ</dt>
<dd><%= job_label(@job) %></dd>
<dt>Kategoria</dt>
<dd><%= link_to @job.category.name, job_category_path(@job.category) %></dd>
<dt>Ocena</dt>
<dd><%= format_rank(@job.rank) %></dd>
<dt>Pracodawca</dt>
<dd><%= link_to @job.company_name, @job.website, :target => "_blank" %></dd>
<dt>Lokalizacja</dt>
<dd><%= link_to @job.localization.name, localization_path(@job.localization) %></dd>
<% unless @job.framework.nil? %>
<dt>Framework</dt>
<dd><%= link_to @job.framework.name, framework_path(@job.framework) %></dd>
<% end %>
<% if @job.widelki_zarobkowe? %>
<dt>WideÅko zarobkowe</dt>
<dd>
<%= "od #{number_to_currency(@job.price_from)}" unless @job.price_from.nil? %>
<%= "do #{number_to_currency(@job.price_to)}" unless @job.price_to.nil? %> na miesiÄ
c, netto
</dd>
<% end %>
<% unless @job.apply_online %>
<dt>Kontakt</dt>
<dd><%= link_to "Formularz kontaktowy", contact_path(:job_id => @job.id) %></dd>
<% end %>
<% unless (@job.regon.nil? || @job.regon.empty?) %>
<dt>REGON</dt>
<dd><%= @job.regon %> </dd>
<% end %>
<% unless (@job.nip.nil? || @job.nip.empty?) %>
<dt>NIP</dt>
<dd><%= @job.nip %> </dd>
<% end %>
<% unless (@job.krs.nil? || @job.krs.empty?) %>
<dt>KRS</dt>
<dd><%= link_to @job.krs, "http://krs.ms.gov.pl/Podmiot.aspx?nrkrs=#{@job.krs}", :target => "_blank" %> </dd>
<% end %>
<dt>Data rozpoczÄcia</dt>
<dd>
<%= l @job.created_at, :format => :long %>
<br />
<abbr title="<%= @job.created_at.xmlschema %>"><%= distance_of_time_in_words_to_now @job.created_at %> temu</abbr>
</dd>
<dt>Data zakoÅczenia</dt>
<dd>
<%= l @job.end_at, :format => :long %>
<br />
za <abbr title="<%= @job.end_at.xmlschema %>"><%= distance_of_time_in_words_to_now(@job.end_at) %></abbr>
</dd>
<dt>WyÅwietlona</dt>
<dd><%= @job.visits_count %> razy</dd>
</dl>
<div class="clear"></div>
</div>
<div>
<div class="title mini">
<h3>Opis oferty</h3>
</div>
- <%= RedCloth.new(@job.description).to_html %>
+ <div>
+ <%= RedCloth.new(@job.description).to_html %>
+ </div>
<p>
<% if permitted_to? :edit, @job %>
<%= link_to 'Edytuj', edit_job_path(@job) %> |
<%= link_to 'Wstecz', jobs_path %>
<% end %>
</p>
</div>
<%= link_to 'Aplikuj online!', new_job_applicant_path(@job), :class => "more" if @job.apply_online %>
</div>
|
macbury/webpraca
|
3b04fad2b60a346dd64a76729c922ca9fb1c3244
|
CSS fix
|
diff --git a/app/stylesheets/ui.less b/app/stylesheets/ui.less
index 3515b7a..a39f3fb 100644
--- a/app/stylesheets/ui.less
+++ b/app/stylesheets/ui.less
@@ -1,600 +1,602 @@
/* Defaults */
@text_color: #393733;
@link_color: #31627E;
@hover_color: #FF5917;
/* Global */
body {
margin: 0;
padding: 0;
font: 12px Arial;
color: @text_color;
overflow: auto;
background: #76787B url('/images/bkg.png') repeat-x top;
}
h1, h2, h3, h4 { margin: 0 0 5px 0; }
a { color: @link_color; cursor: pointer; outline: none !important; text-decoration: none; }
a:hover, a:focus { color: @hover_color; }
a img { border: 0; }
/* Table */
table { border-collapse: collapse; width: 100%; }
td, th {
font-size:11px;
border-bottom:1px solid #eee;
padding:5px;
}
th { text-align:left; font-size:12px; }
thead th { font-weight:bold; color:#666; padding:2px 5px; font-size:11px; background:#e1e1e1 url(/images/nav-bg.gif) top left repeat-x; border-left:1px solid #ddd; border-bottom:1px solid #ddd; }
thead th:first-child { border-left:none !important; }
thead th.optional { font-weight:normal !important; }
tr.alt { background:#f6f6f6; }
/* IDS */
.prices input[type="text"] { width: 50px !important; text-align: right; }
#job_captcha_image, #applicant_captcha_image, .captcha img { margin-bottom: -22px !important; margin-right: 10px !important; }
#job_captcha_solution, #applicant_captcha_solution, .captcha input { width: 200px !important; }
#AdTaily_Widget_Container { padding-top: 5px; }
/* Custom class */
.rounded_corners (@radius: 5px) {
-moz-border-radius: @radius;
-webkit-border-radius: @radius;
border-radius: @radius;
-o-border-radius: @radius;
}
.rounded_corner_top_left(@radius: 5px) { -moz-border-radius-topleft: @radius; -webkit-border-top-left-radius: @radius; border-top-left-radius: @radius; }
.rounded_corner_top_right(@radius: 5px) { -moz-border-radius-topright: @radius; -webkit-border-top-right-radius: @radius; border-top-right-radius: @radius; }
.rounded_corner_bottom_left(@radius: 5px) { -moz-border-radius-bottomleft: @radius; -webkit-border-bottom-left-radius: @radius; border-bottom-left-radius: @radius; }
.rounded_corner_bottom_right(@radius: 5px) { -moz-border-radius-bottomright: @radius; -webkit-border-bottom-right-radius: @radius; border-bottom-right-radius: @radius; }
.reset { margin: 0; padding: 0; list-style: none; }
.text_center { text-align: center; }
.text_right { text-align: right; }
.clear { clear: both; }
.info { text-align: center; color: #ddd; font-size: 28px; font-weight: bold; }
.loader { background: transparent url('/images/ajax.gif') no-repeat center center; height: 20px; display: none; }
.right { float: right; }
.left { float: left; }
/* Flash */
.flash {
background-color: #A4E1A2;
border: 1px solid #DDE3D7;
text-shadow: #C0FDE3 0px 1px 0px;
.rounded_corners(5px);
color: #094808;
margin-top: 10px;
opacity: 0.8;
padding: 10px;
}
.flash.error {
background-color: #AF2B2B;
color: #fff;
border: 1px solid #DA3536;
text-shadow: #000 0px 1px 0px;
}
.flash:hover { opacity: 1.0; }
.flash .dismiss {
background: transparent url('/images/close.png') no-repeat !important;
float: right;
height: 10px;
width: 9px;
text-indent: 9999px;
overflow: hidden;
}
.flash p {
font-weight: normal;
line-height: 15px;
margin: 0px;
}
.flash_error {
background: #AF2B2B url('../images/icon-error.png') 20px center no-repeat;
color: #fff;
border: 1px solid #DA3536;
text-shadow: #000 0px 1px 0px;
}
/* Buttons */
.buttons { margin: 0 5px; }
.button {
background: #DDD url('../images/button.png') repeat-x 0px 0px;
border: 1px solid #999;
display: inline-block;
outline: none;
-webkit-box-shadow: rgba(0, 0, 0, 0.117188) 0px 1px 0px;
}
.button > input[type="button"], .button > input[type="submit"], .button > a {
border: none;
line-height: 23px;
height: 23px;
padding: 0 10px;
color: #333 !important;
font-weight: bold;
text-decoration: none;
font-size: 11px;
cursor: default;
background: transparent;
}
.button:active {
background-color: #ddd;
background-image: none;
}
.button img {
margin-bottom: -4px;
margin-right: 5px;
width: 16px;
height: 16px;
}
.button.right { float: right; }
/* TextFields */
select { min-width: 150px; }
input[type="text"], input[type="password"], textarea {
padding: 4px 3px !important;
border: 1px solid #96A6C5;
color: #000;
}
textarea { height: 200px; min-height: 200px; }
input[type="text"]:focus, input[type="password"]:focus, textarea:focus {
background-color: #e6f7ff;
border-bottom: 1px solid #7FAEFF;
border-right: 1px solid #7FAEFF;
border-left: 1px solid #4478A8;
border-top: 1px solid #4478A8;
}
form > fieldset {
border: 2px solid #ddd !important;
.rounded_corners;
padding: 10px 15px !important;
margin: 10px 5px !important;
}
form > fieldset > legend {
font-weight: bold;
padding: 0 15px 0px 0 !important;
margin-left: -22px !important;
background: #fff;
font-size: 16px;
color: #333 !important;
}
/* Wrapper */
@wrapper_width: 900px;
.wrapper {
margin: 0px auto;
width: @wrapper_width;
min-height: 500px;
}
/* Header */
@header_height: 80px;
.wrapper > .header {
height: @header_height;
width: @wrapper_width;
position:relative;
}
@logo_width: 347px;
@menu_color: #35373A;
@header_link_color: #D8D8D9;
.header > h1#logo {
left: 8px;
position: absolute;
top: 10px;
width: @logo_width;
}
.header > h1#logo a { color: #fff; font: 28px "Trebuchet MS"; font-weight: bold; }
.header > h1#logo a:hover { background: transparent; }
.header > ul.categories {
.reset;
position: absolute;
bottom: 5px;
left: 0px;
width: @content_width;
}
.header > ul.categories li {
display:inline;
margin-left: 3px;
}
.header > ul.categories li.right { float: right; margin-left: 6px; }
.header > ul.categories li > a {
padding: 5px 10px;
margin-top: 5px;
font-size: 13px;
color: @header_link_color;
.rounded_corner_top_left;
.rounded_corner_top_right;
background: @menu_color;
}
.header > ul.categories li > a:hover { background: #5d5f62; }
.header > ul.categories li > .selected { color: #fff; background: #2A2B2D !important; }
.header > ul.menu {
.reset;
.rounded_corner_bottom_left;
.rounded_corner_bottom_right;
position:absolute;
top: 0px;
padding: 5px 10px;
right: 0px;
background: @menu_color;
}
.header > ul.menu li{
display:inline;
margin-left: 3px;
padding-left: 6px;
border-left: 1px dotted #212326;
background-color:transparent;
font-size: 10px;
font-weight: bold;
color: @header_link_color;
}
.header > ul.menu li a { color: @header_link_color; }
.header > ul.menu li a:hover { color: #fff; background: transparent; }
.header > ul.menu li:first-child { border: 0; margin-left: 0; padding-left: 0; }
/* Sidebar */
@sidebar_width: 200px;
.wrapper > .sidebar {
float: right;
width: @sidebar_width;
margin-top: 20px;
}
.wrapper > .sidebar ul { .reset; }
/* content */
@content_padding_right: 10px;
@content_width: @wrapper_width - @sidebar_width - @content_padding_right;
.wrapper > .content {
float: left;
width: @content_width;
padding-right: @content_padding_right;
margin-top: 20px;
}
/*.wrapper > .content p { margin: 0 0 10px 0; padding: 0;} */
/* Box */
.box {
margin-bottom: 10px;
padding: 6px;
background: #9C9C9C;
.rounded_corners(5px);
}
@box_div_border_radius: 4px;
.box > div {
background: #fff;
margin-bottom: 10px;
padding-bottom: 5px;
.rounded_corners(@box_div_border_radius);
}
+.box > div > div { margin: 10px; }
+.box > div > div p { margin: 10px 0; }
.box > div:last-child { margin-bottom: 0; }
@title_height: 39px;
@sidebar_title_height: 29px;
.box .title {
height: @title_height;
.rounded_corner_top_right(@box_div_border_radius);
.rounded_corner_top_left(@box_div_border_radius);
display: block;
background: #fff url('/images/title-header.png') repeat-x bottom;
border-bottom: 1px solid #F1EFBD;
}
.box .title > h2, .box .title > h3 {
margin: 0;
padding: 1px 10px 0 10px;
line-height: @title_height - 1px;
font-weight: normal;
font-size: 18px;
color: #656666;
}
.box .title > h3 {
font-size: 16px;
line-height: @sidebar_title_height - 1px;
}
.box .title > h2 > span, .box .title > h3 > span { color: #8E8F8F; }
.box > div form { margin: 5px !important; }
.box p {
margin: 10px;
}
.sidebar .box .title, .box .title.mini {
height: @sidebar_title_height;
}
/* list */
.list {
.reset;
.clear;
}
.list > li { clear: both; padding: 5px; }
.list > .alt { background:#f6f6f6; }
.list > li > .ranked { font-weight: bold; }
.list > li .handle { cursor: move; margin: 3px 5px 0 5px; }
.list > li > .badge {
float: right;
min-width: 18px;
padding: 2px 3px;
font-weight: bold;
font-size: 10px;
color: #fff;
background: #8798BB;
.rounded_corners(7px);
text-align: center;
}
.list > li > .rank {
.rounded_corners(2px);
text-align: center;
min-width: 18px;
padding: 2px 3px;
font-weight: bold;
font-size: 9px;
float: right;
background: #FFFF98;
border: 1px solid #E2E28C;
margin-top: -1px;
}
.list > li > .date {
font-size: 11px;
font-style: italic;
color: #7C7C7C;
}
/* more button */
.more {
background: #fff url('/images/more.gif') 0% 0% repeat-x;
border: 1px solid #DDD;
border-bottom: 1px solid #AAA;
border-right: 1px solid #AAA;
display: block;
font-size: 14px;
font-weight: bold;
color: inherit;
height: 22px;
line-height: 1.5em;
padding: 6px 0px;
text-align: center;
text-shadow: #fff 1px 1px 1px;
.rounded_corners(6px);
}
.more:hover {
background-position: 0% -78px;
border: 1px solid #BBB;
color: inherit;
}
.more:active {
background-position: 0% -38px;
color: #666;
}
/* Etykiety */
.etykieta {
display: block;
float: left;
font-size: 9px;
margin-right: 5px;
margin-top: -1px;
text-align: center;
width: 60px;
.rounded_corners(2px);
padding: 2px 3px;
color: #fff;
}
.etykieta:hover { color: #fff; }
.etykieta.zdalnie {
background: #357CCB;
border: 1px solid #2C6AB0;
}
.etykieta.zlecenie {
background: #F8854E;
border: 1px solid #D27244;
}
.etykieta.etat {
background: #408000;
border: 1px solid #366E01;
}
.etykieta.praktyka {
background: #FF6;
border: 1px solid #E2E25C;
color: #31627E;
}
.praktyka:hover { color: #31627E; }
.etykieta.wolontariat {
background: #D6D6D6;
border: 1px solid #B1B1B1;
color: #31627E;
}
.wolontariat:hover { color: #31627E; }
/* Pagination */
.pagination { background: white; margin: 5px 5px 0 5px; }
.pagination a, .pagination span {
padding: .2em .5em;
display: block;
float: left;
margin-right: 1px;
}
.pagination span.disabled {
color: #999;
border: 1px solid #DDD;
}
.pagination span.current {
font-weight: bold;
background: #2E6AB1;
color: white;
border: 1px solid #2E6AB1;
}
.pagination a {
text-decoration: none;
color: #105CB6;
border: 1px solid #9AAFE5;
}
.pagination a:hover, .pagination a:focus {
color: #003;
border-color: #003;
background-color: transparent;
}
.pagination .page_info {
background: #2E6AB1;
color: white;
padding: .4em .6em;
width: 22em;
margin-bottom: .3em;
text-align: center;
}
.pagination .page_info b {
color: #003;
background: #6aa6ed;
padding: .1em .25em;
}
.pagination:after {
content: ".";
display: block;
height: 0;
clear: both;
visibility: hidden;
}
* html .pagination { height: 1%; }
*:first-child+html .pagination { overflow: hidden; }
/* describe list */
@dt_width: 180px;
@dt_padding_right: 10px;
@dl_padding_left: 10px;
dl {
padding: 0px;
margin: 10px 0 0 0;
display: block;
}
dl dt {
width: @dt_width;
text-align: right;
color: #888;
float: left;
display: block;
padding: 0 @dt_padding_right 6px 0;
margin: 0;
}
dl dd {
width: @content_width - @dt_width - @dt_padding_right - @dl_padding_left - 15px;
border-left: 1px solid #ccc;
float: left;
padding: 0 0 10px @dl_padding_left;
margin: 0;
}
dl dd:last-child { padding-bottom: 0px; }
dl dd ul {
padding: 5px 0 0 20px;
margin: 0;
}
/* feed icon */
.feed {
float: right;
margin-top: 5px;
margin-right: -3px;
}
/* footer */
.footer {
margin: 10px auto;
width: @wrapper_width;
color: #D8D8D9;
}
.footer strong a { color: #fff; }
.footer a { color: #D8D8D9; }
.footer a:hover { color: #fff; }
.footer .right { margin-top: 3px; }
\ No newline at end of file
|
macbury/webpraca
|
2eca0b89c313123771931aecd8f4819f8e62c1e5
|
Disable job mailer
|
diff --git a/app/controllers/jobs_controller.rb b/app/controllers/jobs_controller.rb
index cba86c4..fe22f7a 100644
--- a/app/controllers/jobs_controller.rb
+++ b/app/controllers/jobs_controller.rb
@@ -1,174 +1,173 @@
class JobsController < ApplicationController
validates_captcha :only => [:create, :new]
ads_pos :bottom
ads_pos :right, :except => [:home, :index, :search]
ads_pos :none, :only => [:home]
def home
@page_title = ['najpopularniejsze oferty', 'najnowsze oferty']
query = Job.active.search
@recent_jobs = query.all(:order => "created_at DESC", :limit => 10, :include => [:localization, :category])
@top_jobs = query.all(:order => "rank DESC, created_at DESC", :limit => 10, :include => [:localization, :category])
end
# GET /jobs
# GET /jobs.xml
def index
@query = Job.search
options = {
:page => params[:page],
:per_page => 25,
:order => "created_at DESC, rank DESC",
:include => [:localization, :category]
}
@query.active
if params[:order] =~ /najpopularniejsze/i
@page_title = ['Najpopularniejsze oferty pracy']
@order = :rank
options[:order] = "rank DESC, created_at DESC"
else
@order = :created_at
@page_title = ['Najnowsze oferty pracy']
options[:order] = "created_at DESC, rank DESC"
end
if params[:category]
@category = Category.find_by_permalink!(params[:category])
@page_title << @category.name
@query.category_id_is(@category.id)
end
if params[:localization]
@localization = Localization.find_by_permalink!(params[:localization])
@page_title << @localization.name
@query.localization_id_is(@localization.id)
end
if params[:framework]
@framework = Framework.find_by_permalink!(params[:framework])
@page_title << @framework.name
options[:include] << :framework
@query.framework_id_is(@framework.id)
end
if params[:type_id]
@type_id = JOB_LABELS.index(params[:type_id]) || 0
@page_title << JOB_LABELS[@type_id]
@query.type_id_is(@type_id)
end
@jobs = @query.paginate(options)
respond_to do |format|
format.html # index.html.erb
format.rss
format.atom
end
end
def search
@page_title = ["Szukaj oferty"]
@search = Job.active.search(params[:search])
if params[:search]
@page_title = ["Znalezione oferty"]
@jobs = @search.paginate( :page => params[:page],
:per_page => 30,
:order => "created_at DESC, rank DESC" )
end
respond_to do |format|
format.html
format.rss { render :action => "index" }
format.atom { render :action => "index" }
end
end
# GET /jobs/1
# GET /jobs/1.xml
def show
@job = Job.find_by_permalink!(params[:id])
@job.visited_by(request.remote_ip)
@category = @job.category
respond_to do |format|
format.html # show.html.erb
end
end
# GET /jobs/new
# GET /jobs/new.xml
def new
@job = Job.new
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @job }
end
end
# POST /jobs
# POST /jobs.xml
def create
@job = Job.new(params[:job])
respond_to do |format|
if @job.save
- @job.send_notification
flash[:notice] = 'Na twój e-mail zostaÅ wysÅany link którym opublikujesz ofertÄ.'
format.html { redirect_to(@job) }
format.xml { render :xml => @job, :status => :created, :location => @job }
else
format.html { render :action => "new" }
format.xml { render :xml => @job.errors, :status => :unprocessable_entity }
end
end
end
# GET /jobs/1/edit
def edit
@job = Job.find_by_permalink_and_token!(params[:id], params[:token])
render :action => "new"
end
# PUT /jobs/1
# PUT /jobs/1.xml
def update
@job = Job.find_by_permalink_and_token!(params[:id], params[:token])
respond_to do |format|
if @job.update_attributes(params[:job])
flash[:notice] = 'Zapisano zmiany w ofercie.'
format.html { redirect_to(@job) }
format.xml { head :ok }
else
format.html { render :action => "new" }
format.xml { render :xml => @job.errors, :status => :unprocessable_entity }
end
end
end
def publish
@job = Job.find_by_permalink_and_token!(params[:id], params[:token])
unless @job.published
@job.publish!
flash[:notice] = "Twoja oferta jest już widoczna!"
end
redirect_to @job
end
# DELETE /jobs/1
# DELETE /jobs/1.xml
def destroy
@job = Job.find_by_permalink_and_token!(params[:id], params[:token])
@job.destroy
flash[:notice] = "Oferta zostaÅa usuniÄta"
respond_to do |format|
format.html { redirect_to(jobs_url) }
format.xml { head :ok }
end
end
end
diff --git a/app/models/job.rb b/app/models/job.rb
index 14792f9..c758f81 100644
--- a/app/models/job.rb
+++ b/app/models/job.rb
@@ -1,175 +1,176 @@
JOB_TYPES = ["zlecenie (konkretna usÅuga do wykonania)", "poszukiwanie wspóÅpracowników / oferta pracy", "wolontariat (praca za reklamy, bannery, itp. lub praca za darmo)", "staż/praktyka"]
JOB_LABELS = ["zlecenie", "etat", "wolontariat", "praktyka"]
JOB_ETAT = 1;
JOB_RANK_VALUES = {
:default => 0.3,
:price => 0.8,
:krs => 0.6,
:nip => 0.5,
:regon => 0.6,
:framework_id => 0.7,
:website => 0.3,
:apply_online => 0.2
}
class Job < ActiveRecord::Base
include ActionController::UrlWriter
xss_terminate
has_permalink :title
named_scope :active, :conditions => ["((jobs.end_at >= ?) AND (jobs.published = ?))", Date.current, true]
named_scope :old, :conditions => ["jobs.end_at < ?", Date.current]
named_scope :has_text, lambda { |text| { :conditions => ["((jobs.title ILIKE ?) OR (jobs.description ILIKE ?))", "%#{text}%", "%#{text}%"] } }
validates_presence_of :title, :description, :email, :company_name, :localization_id, :category_id
validates_length_of :title, :within => 3..255
validates_length_of :description, :within => 10..5000
validates_inclusion_of :type_id, :in => 0..JOB_TYPES.size-1
validates_inclusion_of :dlugosc_trwania, :in => 1..60
validates_numericality_of :price_from,
:greater_than => 0,
:unless => Proc.new { |j| j.price_from.nil? }
validates_numericality_of :price_to,
:greater_than => 0,
:unless => Proc.new { |j| j.price_to.nil? }
validates_format_of :email, :with => Authlogic::Regex.email
validates_format_of :website, :with => /(^$)|(^(http|https):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(([0-9]{1,5})?\/.*)?$)/ix
validates_format_of :regon,
:with => /(^$)|(^[0-9]{7,14}$)/
validates_format_of :nip,
:with => /(^$)|(^\d{2,3}-\d{2,3}-\d{2,3}-\d{2,3}$)/
validates_format_of :krs,
:with => /(^$)|(^\d{10})$/
belongs_to :framework
belongs_to :localization
belongs_to :category
has_many :applicants, :dependent => :delete_all
has_many :visits, :dependent => :delete_all
attr_protected :rank, :permalink, :end_at, :token, :published
attr_accessor :framework_name, :localization_name
before_create :create_from_name, :generate_token
before_save :calculate_rank
+ #after_create :send_notification
def self.find_grouped_by_type
return Job.active.count(:type_id, :group => "type_id")
end
def send_notification
JobMailer.deliver_job_posted(self)
end
def generate_token
alphanumerics = ('a'..'z').to_a.concat(('A'..'Z').to_a.concat(('0'..'9').to_a))
salt = alphanumerics.sort_by{rand}.to_s[0..1024]
self.token = Digest::SHA1.hexdigest("--#{salt}--#{self.id}--#{Date.current}--")
generate_token unless Job.find_by_token(self.token).nil?
end
def calculate_rank
self.rank = 1.0
self.rank += visits_count * 0.01 unless visits_count.nil?
[:regon, :nip, :krs, :framework_id, :website, :apply_online].each do |attribute|
val = send(attribute)
inc = JOB_RANK_VALUES[attribute] || JOB_RANK_VALUES[:default]
self.rank += inc unless (val.nil? || (val.class == String && val.empty?) || (val.class == TrueClass))
end
if widelki_zarobkowe?
self.rank += JOB_RANK_VALUES[:price]
price = price_from || price_to
if price >= 10_000 # ciekawe czy ktoÅ da tyle :P
self.rank += 0.8
elsif price >= 7000
self.rank += 0.7
elsif price >= 5000
self.rank += 0.6
elsif price >= 3000
self.rank += 0.3
elsif price < 2000
if self.type_id == JOB_ETAT
self.rank -= 0.6 # bo nikt za grosze nie chce pracowaÄ
else
self.rank += 0.3 # chyba że to biedny student
end
end
end
end
def widelki_zarobkowe?
((!self.price_from.nil? && self.price_from > 0) || (!self.price_to.nil? && self.price_to > 0))
end
def create_from_name
unless (self.framework_name.nil? || self.framework_name.blank?)
framework = Framework.name_like(self.framework_name).first
framework = Framework.create(:name => self.framework_name) if framework.nil?
self.framework = framework
end
unless (self.localization_name.nil? || self.localization_name.blank?)
localization = Localization.name_like(self.localization_name).first
localization = Localization.create(:name => self.localization_name) if localization.nil?
self.localization = localization
end
end
def dlugosc_trwania
date = created_at.nil? ? Date.current.to_date : created_at.to_date
return (read_attribute(:end_at) - date).to_i rescue 14
end
def dlugosc_trwania=(val)
date = created_at.nil? ? Date.current.to_date : created_at.to_date
write_attribute(:end_at, date+val.to_i.days)
end
def highlited?
self.rank >= 4.75
end
def publish!
self.published = true
save
spawn do
tags = [localization.name, category.name]
tags << framework.name unless framework.nil?
MicroFeed.send :streams => :all,
:msg => "[#{company_name}] - #{title}",
:tags => tags,
:link => seo_job_url(job, :host => "webpraca.net")
end
end
def visited_by(ip)
visit = visits.find_or_create_by_ip(IPAddr.new(ip).to_i)
visits_count += 1 if visit.new_record?
save
end
def to_param
permalink
end
end
|
macbury/webpraca
|
cf53550e6ada1787da09288ad6a4b204b0e44ce4
|
Publish & email
|
diff --git a/app/controllers/jobs_controller.rb b/app/controllers/jobs_controller.rb
index fe22f7a..cba86c4 100644
--- a/app/controllers/jobs_controller.rb
+++ b/app/controllers/jobs_controller.rb
@@ -1,173 +1,174 @@
class JobsController < ApplicationController
validates_captcha :only => [:create, :new]
ads_pos :bottom
ads_pos :right, :except => [:home, :index, :search]
ads_pos :none, :only => [:home]
def home
@page_title = ['najpopularniejsze oferty', 'najnowsze oferty']
query = Job.active.search
@recent_jobs = query.all(:order => "created_at DESC", :limit => 10, :include => [:localization, :category])
@top_jobs = query.all(:order => "rank DESC, created_at DESC", :limit => 10, :include => [:localization, :category])
end
# GET /jobs
# GET /jobs.xml
def index
@query = Job.search
options = {
:page => params[:page],
:per_page => 25,
:order => "created_at DESC, rank DESC",
:include => [:localization, :category]
}
@query.active
if params[:order] =~ /najpopularniejsze/i
@page_title = ['Najpopularniejsze oferty pracy']
@order = :rank
options[:order] = "rank DESC, created_at DESC"
else
@order = :created_at
@page_title = ['Najnowsze oferty pracy']
options[:order] = "created_at DESC, rank DESC"
end
if params[:category]
@category = Category.find_by_permalink!(params[:category])
@page_title << @category.name
@query.category_id_is(@category.id)
end
if params[:localization]
@localization = Localization.find_by_permalink!(params[:localization])
@page_title << @localization.name
@query.localization_id_is(@localization.id)
end
if params[:framework]
@framework = Framework.find_by_permalink!(params[:framework])
@page_title << @framework.name
options[:include] << :framework
@query.framework_id_is(@framework.id)
end
if params[:type_id]
@type_id = JOB_LABELS.index(params[:type_id]) || 0
@page_title << JOB_LABELS[@type_id]
@query.type_id_is(@type_id)
end
@jobs = @query.paginate(options)
respond_to do |format|
format.html # index.html.erb
format.rss
format.atom
end
end
def search
@page_title = ["Szukaj oferty"]
@search = Job.active.search(params[:search])
if params[:search]
@page_title = ["Znalezione oferty"]
@jobs = @search.paginate( :page => params[:page],
:per_page => 30,
:order => "created_at DESC, rank DESC" )
end
respond_to do |format|
format.html
format.rss { render :action => "index" }
format.atom { render :action => "index" }
end
end
# GET /jobs/1
# GET /jobs/1.xml
def show
@job = Job.find_by_permalink!(params[:id])
@job.visited_by(request.remote_ip)
@category = @job.category
respond_to do |format|
format.html # show.html.erb
end
end
# GET /jobs/new
# GET /jobs/new.xml
def new
@job = Job.new
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @job }
end
end
# POST /jobs
# POST /jobs.xml
def create
@job = Job.new(params[:job])
respond_to do |format|
if @job.save
+ @job.send_notification
flash[:notice] = 'Na twój e-mail zostaÅ wysÅany link którym opublikujesz ofertÄ.'
format.html { redirect_to(@job) }
format.xml { render :xml => @job, :status => :created, :location => @job }
else
format.html { render :action => "new" }
format.xml { render :xml => @job.errors, :status => :unprocessable_entity }
end
end
end
# GET /jobs/1/edit
def edit
@job = Job.find_by_permalink_and_token!(params[:id], params[:token])
render :action => "new"
end
# PUT /jobs/1
# PUT /jobs/1.xml
def update
@job = Job.find_by_permalink_and_token!(params[:id], params[:token])
respond_to do |format|
if @job.update_attributes(params[:job])
flash[:notice] = 'Zapisano zmiany w ofercie.'
format.html { redirect_to(@job) }
format.xml { head :ok }
else
format.html { render :action => "new" }
format.xml { render :xml => @job.errors, :status => :unprocessable_entity }
end
end
end
def publish
@job = Job.find_by_permalink_and_token!(params[:id], params[:token])
unless @job.published
@job.publish!
flash[:notice] = "Twoja oferta jest już widoczna!"
end
redirect_to @job
end
# DELETE /jobs/1
# DELETE /jobs/1.xml
def destroy
@job = Job.find_by_permalink_and_token!(params[:id], params[:token])
@job.destroy
flash[:notice] = "Oferta zostaÅa usuniÄta"
respond_to do |format|
format.html { redirect_to(jobs_url) }
format.xml { head :ok }
end
end
end
diff --git a/app/models/job.rb b/app/models/job.rb
index 555d2c5..14792f9 100644
--- a/app/models/job.rb
+++ b/app/models/job.rb
@@ -1,176 +1,175 @@
JOB_TYPES = ["zlecenie (konkretna usÅuga do wykonania)", "poszukiwanie wspóÅpracowników / oferta pracy", "wolontariat (praca za reklamy, bannery, itp. lub praca za darmo)", "staż/praktyka"]
JOB_LABELS = ["zlecenie", "etat", "wolontariat", "praktyka"]
JOB_ETAT = 1;
JOB_RANK_VALUES = {
:default => 0.3,
:price => 0.8,
:krs => 0.6,
:nip => 0.5,
:regon => 0.6,
:framework_id => 0.7,
:website => 0.3,
:apply_online => 0.2
}
class Job < ActiveRecord::Base
include ActionController::UrlWriter
xss_terminate
has_permalink :title
named_scope :active, :conditions => ["((jobs.end_at >= ?) AND (jobs.published = ?))", Date.current, true]
named_scope :old, :conditions => ["jobs.end_at < ?", Date.current]
named_scope :has_text, lambda { |text| { :conditions => ["((jobs.title ILIKE ?) OR (jobs.description ILIKE ?))", "%#{text}%", "%#{text}%"] } }
validates_presence_of :title, :description, :email, :company_name, :localization_id, :category_id
validates_length_of :title, :within => 3..255
validates_length_of :description, :within => 10..5000
validates_inclusion_of :type_id, :in => 0..JOB_TYPES.size-1
validates_inclusion_of :dlugosc_trwania, :in => 1..60
validates_numericality_of :price_from,
:greater_than => 0,
:unless => Proc.new { |j| j.price_from.nil? }
validates_numericality_of :price_to,
:greater_than => 0,
:unless => Proc.new { |j| j.price_to.nil? }
validates_format_of :email, :with => Authlogic::Regex.email
validates_format_of :website, :with => /(^$)|(^(http|https):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(([0-9]{1,5})?\/.*)?$)/ix
validates_format_of :regon,
:with => /(^$)|(^[0-9]{7,14}$)/
validates_format_of :nip,
:with => /(^$)|(^\d{2,3}-\d{2,3}-\d{2,3}-\d{2,3}$)/
validates_format_of :krs,
:with => /(^$)|(^\d{10})$/
belongs_to :framework
belongs_to :localization
belongs_to :category
has_many :applicants, :dependent => :delete_all
has_many :visits, :dependent => :delete_all
attr_protected :rank, :permalink, :end_at, :token, :published
attr_accessor :framework_name, :localization_name
before_create :create_from_name, :generate_token
before_save :calculate_rank
- after_create :send_notification
def self.find_grouped_by_type
return Job.active.count(:type_id, :group => "type_id")
end
def send_notification
JobMailer.deliver_job_posted(self)
end
def generate_token
alphanumerics = ('a'..'z').to_a.concat(('A'..'Z').to_a.concat(('0'..'9').to_a))
salt = alphanumerics.sort_by{rand}.to_s[0..1024]
self.token = Digest::SHA1.hexdigest("--#{salt}--#{self.id}--#{Date.current}--")
generate_token unless Job.find_by_token(self.token).nil?
end
def calculate_rank
self.rank = 1.0
self.rank += visits_count * 0.01 unless visits_count.nil?
[:regon, :nip, :krs, :framework_id, :website, :apply_online].each do |attribute|
val = send(attribute)
inc = JOB_RANK_VALUES[attribute] || JOB_RANK_VALUES[:default]
self.rank += inc unless (val.nil? || (val.class == String && val.empty?) || (val.class == TrueClass))
end
if widelki_zarobkowe?
self.rank += JOB_RANK_VALUES[:price]
price = price_from || price_to
if price >= 10_000 # ciekawe czy ktoÅ da tyle :P
self.rank += 0.8
elsif price >= 7000
self.rank += 0.7
elsif price >= 5000
self.rank += 0.6
elsif price >= 3000
self.rank += 0.3
elsif price < 2000
if self.type_id == JOB_ETAT
self.rank -= 0.6 # bo nikt za grosze nie chce pracowaÄ
else
self.rank += 0.3 # chyba że to biedny student
end
end
end
end
def widelki_zarobkowe?
((!self.price_from.nil? && self.price_from > 0) || (!self.price_to.nil? && self.price_to > 0))
end
def create_from_name
unless (self.framework_name.nil? || self.framework_name.blank?)
framework = Framework.name_like(self.framework_name).first
framework = Framework.create(:name => self.framework_name) if framework.nil?
self.framework = framework
end
unless (self.localization_name.nil? || self.localization_name.blank?)
localization = Localization.name_like(self.localization_name).first
localization = Localization.create(:name => self.localization_name) if localization.nil?
self.localization = localization
end
end
def dlugosc_trwania
date = created_at.nil? ? Date.current.to_date : created_at.to_date
return (read_attribute(:end_at) - date).to_i rescue 14
end
def dlugosc_trwania=(val)
date = created_at.nil? ? Date.current.to_date : created_at.to_date
write_attribute(:end_at, date+val.to_i.days)
end
def highlited?
self.rank >= 4.75
end
def publish!
self.published = true
save
spawn do
tags = [localization.name, category.name]
tags << framework.name unless framework.nil?
MicroFeed.send :streams => :all,
:msg => "[#{company_name}] - #{title}",
:tags => tags,
:link => seo_job_url(job, :host => "webpraca.net")
end
end
def visited_by(ip)
visit = visits.find_or_create_by_ip(IPAddr.new(ip).to_i)
visits_count += 1 if visit.new_record?
save
end
def to_param
permalink
end
end
diff --git a/lib/tasks/webpraca.rake b/lib/tasks/webpraca.rake
index d91e431..da7bc38 100644
--- a/lib/tasks/webpraca.rake
+++ b/lib/tasks/webpraca.rake
@@ -1,67 +1,68 @@
require 'highline/import'
def ask_for_password(message)
val = ask(message) {|q| q.echo = false}
if val.nil? || val.empty?
return ask_for_password(message)
else
return val
end
end
def ask(message)
puts "#{message}:"
val = STDIN.gets.chomp
if val.nil? || val.empty?
return ask(message)
else
return val
end
end
def render_errors(obj)
index = 0
obj.errors.each_full do |msg|
index += 1
puts "#{index}. #{msg}"
end
end
namespace :webpraca do
namespace :clear do
task :applicants => :environment do
Applicant.all.each(&:destroy)
end
task :visits => :environment do
Visit.all.each(&:destroy)
end
end
namespace :jobs do
task :remove_old => :environment do
Job.old.each(&:destroy)
end
task :publish_all => :environment do
Job.all(:conditions => { :published => false }).each do |job|
+ job.send_notification
job.publish!
end
end
end
namespace :admin do
task :create => :environment do
puts "Creating new admin user"
user = User.new
user.email = ask("Enter E-Mail")
user.password = ask_for_password("Enter Password")
user.password_confirmation = ask_for_password("Enter password confirmation")
if user.save
puts "Created admin user!"
else
render_errors(user)
end
end
end
end
\ No newline at end of file
|
macbury/webpraca
|
7e0829b6ad860d862dfa265ff6ce6a24b7d9ce3e
|
Twitter & facebook
|
diff --git a/app/models/contact_mailer.rb b/app/models/contact_mailer.rb
index d7dca0f..567c70a 100644
--- a/app/models/contact_mailer.rb
+++ b/app/models/contact_mailer.rb
@@ -1,14 +1,14 @@
class ContactMailer < ActionMailer::Base
include ExceptionNotifiable
def contact_notification(contact_handler)
@recipients = contact_handler.job.nil? ? ExceptionNotifier.exception_recipients : contact_handler.job.email
- @from = contact_handler.email
+ @from = ActionMailer::Base.smtp_settings[:from]
@subject = "Kontakt od: #{contact_handler.email}"
@body[:contact_handler] = contact_handler
end
end
\ No newline at end of file
diff --git a/app/views/layouts/application.html.erb b/app/views/layouts/application.html.erb
index 4666f0f..da46472 100644
--- a/app/views/layouts/application.html.erb
+++ b/app/views/layouts/application.html.erb
@@ -1,79 +1,80 @@
<!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" lang="pl">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<%= display_meta_tags :site => WebSiteConfig['website']['name'] %>
<meta name="viewport" content="width=900" />
<%= rss_link("RSS", jobs_url(:format => :rss)) %>
<%= rss_link("ATOM", jobs_url(:format => :atom)) %>
<%= javascript_tag "window._token = '#{form_authenticity_token}'" %>
<%= javascript_include_merged :base %>
<%= stylesheet_link_merged :base %>
</head>
<body>
<div class="wrapper">
<div class="header">
<h1 id="logo"><%= link_to WebSiteConfig['website']['name'], root_path %></h1>
<ul class="categories">
<li class="right">
<%= link_to "Najpopularniejsze", seo_jobs_path(:order => 'najpopularniejsze', :category => params[:category]), :class => (!@order.nil? && @order == :rank) ? "selected" : "normal" %>
</li>
<li class="right">
<%= link_to "Najnowsze", seo_jobs_path(:order => 'najnowsze', :category => params[:category] ), :class => (!@order.nil? && @order == :created_at) ? "selected" : "normal" %>
</li>
<% for category in Category.all(:order => "position") %>
<li>
<%= link_to category.name, seo_jobs_path(:order => params[:order], :category => category.permalink), :class => (!@category.nil? && @category.id == category.id) ? "selected" : "normal" %>
</li>
<% end %>
</ul>
<ul class="menu">
<li><%= link_to "Strona gÅówna", root_path %></li>
<li><%= link_to "Szukaj", search_jobs_path %></li>
<li><%= link_to "Informacje", "/strona/informacje/" %></li>
<li><%= link_to "Regulamin", "/strona/regulamin/" %></li>
+ <li><%= link_to "Obserwuj nas", "/strona/obserwuj-nas" %></li>
<li><%= link_to "Kontakt", contact_path %></li>
</ul>
</div>
<%- flash.each do |name, msg| -%>
<div class="<%= "flash #{name}" %>">
<a href="#" class="dismiss">X</a>
<p><%= msg %></p>
</div>
<%- end -%>
<div class="sidebar">
<div class="box">
<%= link_to "Dodaj ofertÄ za DARMO!", new_job_path, :id => "add_job", :class => "more" %>
</div>
<%= yield :sidebar %>
<% if @ads_pos == :right %>
<div class="box">
<div>
<%= render :partial => "/shared/ads" %>
</div>
</div>
<% end %>
</div>
<div class="content">
<%= yield %>
<% if @ads_pos == :bottom %>
<div class="box">
<div>
<%= render :partial => "/shared/ads" %>
</div>
</div>
<% end %>
</div>
<div class="clear"></div>
</div>
<%= render :partial => "/shared/footer" %>
<%= WebSiteConfig['js']['google_analytics'] %>
</body>
</html>
\ No newline at end of file
diff --git a/doc/obserwuj.txt b/doc/obserwuj.txt
new file mode 100644
index 0000000..2017a07
--- /dev/null
+++ b/doc/obserwuj.txt
@@ -0,0 +1,8 @@
+# "RSS":/jobs.rss
+# "Atom":/jobs.atom
+# "Twitter":http://twitter.com/webpraca
+# "Facebook":http://www.facebook.com/pages/webpracanet/385396655455
+# "Blip":http://webpraca.blip.pl
+# "Flaker":http://flaker.pl/webpraca
+# "Spinacz":http://spinacz.pl/webpraca
+# "Pinger":http://webpraca.pinger.pl/
diff --git a/vendor/plugins/MicroFeed/lib/feeds/twitter_feed.rb b/vendor/plugins/MicroFeed/lib/feeds/twitter_feed.rb
new file mode 100644
index 0000000..8ab1165
--- /dev/null
+++ b/vendor/plugins/MicroFeed/lib/feeds/twitter_feed.rb
@@ -0,0 +1,29 @@
+class TwitterFeed
+ attr_accessor :user, :password
+
+ def setup(config={})
+ self.user = config['login']
+ self.password = config['password']
+ end
+
+ def send(options={})
+ headers = {
+ "User-Agent" => "Ruby v1.8",
+ "X-Twitter-Client" => "Ruby",
+ "X-Twitter-Client-Version" => "1.8"
+ }
+
+ url = URI.parse("http://twitter.com/statuses/update.xml")
+ req = Net::HTTP::Post.new(url.path, headers)
+
+ req.basic_auth(self.user, self.password)
+
+ body = options[:msg]
+ body += " - " + options[:link] if options[:link]
+ body += " " + options[:tags].map { |tag| "##{tag}" }.join(', ') if options[:tags]
+
+ req.set_form_data({'status' => body, 'source' => 'webpage'})
+
+ response = Net::HTTP.new(url.host, url.port).start { |http| http.request(req) }
+ end
+end
\ No newline at end of file
diff --git a/vendor/plugins/MicroFeed/lib/micro_feed.rb b/vendor/plugins/MicroFeed/lib/micro_feed.rb
index a9b217b..294766a 100644
--- a/vendor/plugins/MicroFeed/lib/micro_feed.rb
+++ b/vendor/plugins/MicroFeed/lib/micro_feed.rb
@@ -1,43 +1,44 @@
require "net/http"
require "uri"
require "feeds/blip_feed"
require "feeds/flaker_feed"
require "feeds/spinacz_feed"
require "feeds/pinger_feed"
+require "feeds/twitter_feed"
class MicroFeed
MICRO_FEED_CONFIG = YAML.load_file("#{RAILS_ROOT}/config/micro_feed.yml")
# WysyÅa wiadomoÅÄ do podanych serwisów mikroblogowych
# DostÄpne opcje:
# * +:streams+: serwisy do których ma dojÅÄ wiadomoÅÄ(:all, [:blip, :flaker], :blip)
# * +msg+: treÅÄ wiadomoÅci
# * +link+: link do strony
# * +tags+: tablica z tagami(np. ['sport', 'telewizja'])
def self.send(config={})
default = {
:streams => :all,
:msg => "Hello World!",
:link => nil,
:tags => nil
}.merge!(config)
available_streams = MICRO_FEED_CONFIG.map { |stream, config| stream.to_sym }
if default[:streams] == :all
send_to = available_streams
elsif default[:streams].class == Symbol
send_to = available_streams.include?(default[:streams].to_sym) ? [default[:streams]] : available_streams
else
send_to = default[:streams].reject { |stream| !available_streams.include?(stream.to_sym) }
end
send_to.each do |stream_name|
config = MICRO_FEED_CONFIG[stream_name.to_s]
sender = eval("#{stream_name.to_s.camelize}Feed").new
sender.setup(config)
sender.send(default)
end
end
end
\ No newline at end of file
diff --git a/vendor/plugins/MicroFeed/micro_feed.yml b/vendor/plugins/MicroFeed/micro_feed.yml
index 92e6c20..2c1452f 100644
--- a/vendor/plugins/MicroFeed/micro_feed.yml
+++ b/vendor/plugins/MicroFeed/micro_feed.yml
@@ -1,14 +1,18 @@
blip:
login: username
password: secret
flaker:
login: username
password: secret
pinger:
login: username
password: secret
+twitter:
+ login: username
+ password: secret
+
spinacz:
hash: 139c82e0679b64132f528fa71a9ee8d1
\ No newline at end of file
|
macbury/webpraca
|
456015cb31567716c6efa2a588bdc9e8cfa3cfeb
|
NewRelic gem
|
diff --git a/app/models/contact_mailer.rb b/app/models/contact_mailer.rb
index d248cd6..d7dca0f 100644
--- a/app/models/contact_mailer.rb
+++ b/app/models/contact_mailer.rb
@@ -1,14 +1,14 @@
class ContactMailer < ActionMailer::Base
include ExceptionNotifiable
def contact_notification(contact_handler)
@recipients = contact_handler.job.nil? ? ExceptionNotifier.exception_recipients : contact_handler.job.email
@from = contact_handler.email
- @subject = "Kontakt od: #{contact_handler.subject}"
+ @subject = "Kontakt od: #{contact_handler.email}"
@body[:contact_handler] = contact_handler
end
end
\ No newline at end of file
diff --git a/config/environment.rb b/config/environment.rb
index 65444dc..c6ea631 100644
--- a/config/environment.rb
+++ b/config/environment.rb
@@ -1,48 +1,49 @@
# Be sure to restart your server when you modify this file
# Specifies gem version of Rails to use when vendor/rails is not present
# Bootstrap the Rails environment, frameworks, and default configuration
require File.join(File.dirname(__FILE__), 'boot')
Rails::Initializer.run do |config|
config.gem 'sitemap_generator', :lib => false, :source => 'http://gemcutter.org'
config.gem 'less', :source => 'http://gemcutter.org', :lib => false
config.gem 'meta-tags', :lib => 'meta_tags', :source => 'http://gemcutter.org'
config.gem 'declarative_authorization'
config.gem 'searchlogic'
config.gem 'RedCloth', :lib => "redcloth"
config.gem 'authlogic'
+ config.gem "newrelic_rpm"
config.gem 'whenever', :lib => false, :source => 'http://gemcutter.org/'
config.gem 'highline', :lib => false
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Add additional load paths for your own custom dirs
# config.load_paths += %W( #{RAILS_ROOT}/extras )
# Specify gems that this application depends on and have them installed with rake gems:install
# config.gem "bj"
# config.gem "hpricot", :version => '0.6', :source => "http://code.whytheluckystiff.net"
# config.gem "sqlite3-ruby", :lib => "sqlite3"
# config.gem "aws-s3", :lib => "aws/s3"
# Only load the plugins named here, in the order given (default is alphabetical).
# :all can be used as a placeholder for all plugins not explicitly named
#config.plugins = [ :all, :less, 'less-rails' ]
# Skip frameworks you're not going to use. To use Rails without a database,
# you must remove the Active Record framework.
# config.frameworks -= [ :active_record, :active_resource, :action_mailer ]
# Activate observers that should always be running
# config.active_record.observers = :cacher, :garbage_collector, :forum_observer
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names.
config.time_zone = 'Warsaw'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}')]
config.i18n.default_locale = :pl
end
\ No newline at end of file
diff --git a/config/initializers/mailer.rb b/config/initializers/mailer.rb
index 8b01c77..57fa305 100644
--- a/config/initializers/mailer.rb
+++ b/config/initializers/mailer.rb
@@ -1,7 +1,8 @@
require "smtp_tls"
ActionMailer::Base.delivery_method = :smtp
ActionMailer::Base.default_charset = 'utf-8'
ActionMailer::Base.perform_deliveries = true
+ActionMailer::Base.raise_delivery_errors = true
ActionMailer::Base.smtp_settings = YAML.load_file("#{RAILS_ROOT}/config/mailer.yml")[Rails.env]
ActionMailer::Base.smtp_settings[:tsl] = true
ActionMailer::Base.smtp_settings[:authentication] = :login
\ No newline at end of file
diff --git a/public/stylesheets/scaffold.css b/public/stylesheets/scaffold.css
deleted file mode 100644
index 093c209..0000000
--- a/public/stylesheets/scaffold.css
+++ /dev/null
@@ -1,54 +0,0 @@
-body { background-color: #fff; color: #333; }
-
-body, p, ol, ul, td {
- font-family: verdana, arial, helvetica, sans-serif;
- font-size: 13px;
- line-height: 18px;
-}
-
-pre {
- background-color: #eee;
- padding: 10px;
- font-size: 11px;
-}
-
-a { color: #000; }
-a:visited { color: #666; }
-a:hover { color: #fff; background-color:#000; }
-
-.fieldWithErrors {
- padding: 2px;
- background-color: red;
- display: table;
-}
-
-#errorExplanation {
- width: 400px;
- border: 2px solid red;
- padding: 7px;
- padding-bottom: 12px;
- margin-bottom: 20px;
- background-color: #f0f0f0;
-}
-
-#errorExplanation h2 {
- text-align: left;
- font-weight: bold;
- padding: 5px 5px 5px 15px;
- font-size: 12px;
- margin: -7px;
- background-color: #c00;
- color: #fff;
-}
-
-#errorExplanation p {
- color: #333;
- margin-bottom: 0;
- padding: 5px;
-}
-
-#errorExplanation ul li {
- font-size: 12px;
- list-style: square;
-}
-
diff --git a/vendor/plugins/micro_feed b/vendor/plugins/micro_feed
deleted file mode 160000
index 42b4591..0000000
--- a/vendor/plugins/micro_feed
+++ /dev/null
@@ -1 +0,0 @@
-Subproject commit 42b45915abba55bc1899f362a87108eed4959a10
diff --git a/vendor/plugins/stupid_simple_config b/vendor/plugins/stupid_simple_config
deleted file mode 160000
index a429f6c..0000000
--- a/vendor/plugins/stupid_simple_config
+++ /dev/null
@@ -1 +0,0 @@
-Subproject commit a429f6cea09c438f0cd28ffe126d6400352936a3
|
macbury/webpraca
|
12225cd94e576587679b8000f3ca042d9c09097c
|
Skip newrelic config
|
diff --git a/.gitignore b/.gitignore
index 53aa268..bdfc986 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,11 +1,12 @@
.DS_Store
log/*.log
tmp/**/*
public/*.xml.gz
public/images/captchas/*
config/database.yml
config/mailer.yml
config/exception_notifer.yml
config/micro_feed.yml
+config/newrelic.yml
config/deploy.rb
db/*.sqlite3
|
macbury/webpraca
|
3b4694766faed599313c7ff71ac761a5a4a7edda
|
rails env
|
diff --git a/config/schedule.rb b/config/schedule.rb
index ad1eed8..6d024b6 100644
--- a/config/schedule.rb
+++ b/config/schedule.rb
@@ -1,9 +1,9 @@
-set :environment, Rails.env
+set :environment, "production"
every :hour do # Many shortcuts available: :hour, :day, :month, :year, :reboot
rake "validates_captcha:create_static_images COUNT=50"
end
every 1.day, :at => '1:30 am' do
rake "sitemap:refresh"
rake "webpraca:jobs:remove_old"
end
\ No newline at end of file
|
macbury/webpraca
|
b7b3eb342df8958439eb0649c8cdaa23940895a2
|
Mailer megiteam
|
diff --git a/config/initializers/mailer.rb b/config/initializers/mailer.rb
index 652fdd1..8b01c77 100644
--- a/config/initializers/mailer.rb
+++ b/config/initializers/mailer.rb
@@ -1,5 +1,7 @@
require "smtp_tls"
ActionMailer::Base.delivery_method = :smtp
ActionMailer::Base.default_charset = 'utf-8'
ActionMailer::Base.perform_deliveries = true
-ActionMailer::Base.smtp_settings = YAML.load_file("#{RAILS_ROOT}/config/mailer.yml")[Rails.env]
\ No newline at end of file
+ActionMailer::Base.smtp_settings = YAML.load_file("#{RAILS_ROOT}/config/mailer.yml")[Rails.env]
+ActionMailer::Base.smtp_settings[:tsl] = true
+ActionMailer::Base.smtp_settings[:authentication] = :login
\ No newline at end of file
diff --git a/push.sh b/push.sh
index 547e53a..d360c84 100644
--- a/push.sh
+++ b/push.sh
@@ -1,9 +1,9 @@
#!/usr/bin/env bash
-git push origin deploy
+git push origin master
-export branch=deploy
+export branch=master
env DEPLOY='production' cap deploy
env DEPLOY='production' cap deploy:migrate
cap deploy:cleanup
\ No newline at end of file
|
macbury/webpraca
|
684da7e786e897bf6b78992b6dba6d518f17922d
|
Publish tasks fix
|
diff --git a/app/models/job.rb b/app/models/job.rb
index 879eb15..555d2c5 100644
--- a/app/models/job.rb
+++ b/app/models/job.rb
@@ -1,174 +1,176 @@
JOB_TYPES = ["zlecenie (konkretna usÅuga do wykonania)", "poszukiwanie wspóÅpracowników / oferta pracy", "wolontariat (praca za reklamy, bannery, itp. lub praca za darmo)", "staż/praktyka"]
JOB_LABELS = ["zlecenie", "etat", "wolontariat", "praktyka"]
JOB_ETAT = 1;
JOB_RANK_VALUES = {
:default => 0.3,
:price => 0.8,
:krs => 0.6,
:nip => 0.5,
:regon => 0.6,
:framework_id => 0.7,
:website => 0.3,
:apply_online => 0.2
}
class Job < ActiveRecord::Base
+ include ActionController::UrlWriter
xss_terminate
has_permalink :title
named_scope :active, :conditions => ["((jobs.end_at >= ?) AND (jobs.published = ?))", Date.current, true]
named_scope :old, :conditions => ["jobs.end_at < ?", Date.current]
named_scope :has_text, lambda { |text| { :conditions => ["((jobs.title ILIKE ?) OR (jobs.description ILIKE ?))", "%#{text}%", "%#{text}%"] } }
validates_presence_of :title, :description, :email, :company_name, :localization_id, :category_id
validates_length_of :title, :within => 3..255
validates_length_of :description, :within => 10..5000
validates_inclusion_of :type_id, :in => 0..JOB_TYPES.size-1
validates_inclusion_of :dlugosc_trwania, :in => 1..60
validates_numericality_of :price_from,
:greater_than => 0,
:unless => Proc.new { |j| j.price_from.nil? }
validates_numericality_of :price_to,
:greater_than => 0,
:unless => Proc.new { |j| j.price_to.nil? }
validates_format_of :email, :with => Authlogic::Regex.email
validates_format_of :website, :with => /(^$)|(^(http|https):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(([0-9]{1,5})?\/.*)?$)/ix
validates_format_of :regon,
:with => /(^$)|(^[0-9]{7,14}$)/
validates_format_of :nip,
:with => /(^$)|(^\d{2,3}-\d{2,3}-\d{2,3}-\d{2,3}$)/
validates_format_of :krs,
:with => /(^$)|(^\d{10})$/
belongs_to :framework
belongs_to :localization
belongs_to :category
has_many :applicants, :dependent => :delete_all
has_many :visits, :dependent => :delete_all
attr_protected :rank, :permalink, :end_at, :token, :published
attr_accessor :framework_name, :localization_name
before_create :create_from_name, :generate_token
before_save :calculate_rank
after_create :send_notification
def self.find_grouped_by_type
return Job.active.count(:type_id, :group => "type_id")
end
def send_notification
JobMailer.deliver_job_posted(self)
end
def generate_token
alphanumerics = ('a'..'z').to_a.concat(('A'..'Z').to_a.concat(('0'..'9').to_a))
salt = alphanumerics.sort_by{rand}.to_s[0..1024]
self.token = Digest::SHA1.hexdigest("--#{salt}--#{self.id}--#{Date.current}--")
generate_token unless Job.find_by_token(self.token).nil?
end
def calculate_rank
self.rank = 1.0
self.rank += visits_count * 0.01 unless visits_count.nil?
[:regon, :nip, :krs, :framework_id, :website, :apply_online].each do |attribute|
val = send(attribute)
inc = JOB_RANK_VALUES[attribute] || JOB_RANK_VALUES[:default]
self.rank += inc unless (val.nil? || (val.class == String && val.empty?) || (val.class == TrueClass))
end
if widelki_zarobkowe?
self.rank += JOB_RANK_VALUES[:price]
price = price_from || price_to
if price >= 10_000 # ciekawe czy ktoÅ da tyle :P
self.rank += 0.8
elsif price >= 7000
self.rank += 0.7
elsif price >= 5000
self.rank += 0.6
elsif price >= 3000
self.rank += 0.3
elsif price < 2000
if self.type_id == JOB_ETAT
self.rank -= 0.6 # bo nikt za grosze nie chce pracowaÄ
else
self.rank += 0.3 # chyba że to biedny student
end
end
end
end
def widelki_zarobkowe?
((!self.price_from.nil? && self.price_from > 0) || (!self.price_to.nil? && self.price_to > 0))
end
def create_from_name
unless (self.framework_name.nil? || self.framework_name.blank?)
framework = Framework.name_like(self.framework_name).first
framework = Framework.create(:name => self.framework_name) if framework.nil?
self.framework = framework
end
unless (self.localization_name.nil? || self.localization_name.blank?)
localization = Localization.name_like(self.localization_name).first
localization = Localization.create(:name => self.localization_name) if localization.nil?
self.localization = localization
end
end
def dlugosc_trwania
date = created_at.nil? ? Date.current.to_date : created_at.to_date
return (read_attribute(:end_at) - date).to_i rescue 14
end
def dlugosc_trwania=(val)
date = created_at.nil? ? Date.current.to_date : created_at.to_date
write_attribute(:end_at, date+val.to_i.days)
end
def highlited?
self.rank >= 4.75
end
def publish!
self.published = true
save
+
spawn do
tags = [localization.name, category.name]
tags << framework.name unless framework.nil?
MicroFeed.send :streams => :all,
:msg => "[#{company_name}] - #{title}",
:tags => tags,
:link => seo_job_url(job, :host => "webpraca.net")
end
end
def visited_by(ip)
visit = visits.find_or_create_by_ip(IPAddr.new(ip).to_i)
visits_count += 1 if visit.new_record?
save
end
def to_param
permalink
end
end
diff --git a/lib/tasks/webpraca.rake b/lib/tasks/webpraca.rake
index 69dffee..d91e431 100644
--- a/lib/tasks/webpraca.rake
+++ b/lib/tasks/webpraca.rake
@@ -1,67 +1,67 @@
require 'highline/import'
def ask_for_password(message)
val = ask(message) {|q| q.echo = false}
if val.nil? || val.empty?
return ask_for_password(message)
else
return val
end
end
def ask(message)
puts "#{message}:"
val = STDIN.gets.chomp
if val.nil? || val.empty?
return ask(message)
else
return val
end
end
def render_errors(obj)
index = 0
obj.errors.each_full do |msg|
index += 1
puts "#{index}. #{msg}"
end
end
namespace :webpraca do
namespace :clear do
task :applicants => :environment do
Applicant.all.each(&:destroy)
end
task :visits => :environment do
Visit.all.each(&:destroy)
end
end
namespace :jobs do
task :remove_old => :environment do
Job.old.each(&:destroy)
end
task :publish_all => :environment do
- Job.all.each do |job|
+ Job.all(:conditions => { :published => false }).each do |job|
job.publish!
end
end
end
namespace :admin do
task :create => :environment do
puts "Creating new admin user"
user = User.new
user.email = ask("Enter E-Mail")
user.password = ask_for_password("Enter Password")
user.password_confirmation = ask_for_password("Enter password confirmation")
if user.save
puts "Created admin user!"
else
render_errors(user)
end
end
end
end
\ No newline at end of file
|
macbury/webpraca
|
926d316f1dbc490bb8be611b9eb17517d5e226c5
|
Publish task
|
diff --git a/app/controllers/jobs_controller.rb b/app/controllers/jobs_controller.rb
index 6e9272c..fe22f7a 100644
--- a/app/controllers/jobs_controller.rb
+++ b/app/controllers/jobs_controller.rb
@@ -1,185 +1,173 @@
class JobsController < ApplicationController
validates_captcha :only => [:create, :new]
ads_pos :bottom
ads_pos :right, :except => [:home, :index, :search]
ads_pos :none, :only => [:home]
def home
@page_title = ['najpopularniejsze oferty', 'najnowsze oferty']
query = Job.active.search
@recent_jobs = query.all(:order => "created_at DESC", :limit => 10, :include => [:localization, :category])
@top_jobs = query.all(:order => "rank DESC, created_at DESC", :limit => 10, :include => [:localization, :category])
end
# GET /jobs
# GET /jobs.xml
def index
@query = Job.search
options = {
:page => params[:page],
:per_page => 25,
:order => "created_at DESC, rank DESC",
:include => [:localization, :category]
}
@query.active
if params[:order] =~ /najpopularniejsze/i
@page_title = ['Najpopularniejsze oferty pracy']
@order = :rank
options[:order] = "rank DESC, created_at DESC"
else
@order = :created_at
@page_title = ['Najnowsze oferty pracy']
options[:order] = "created_at DESC, rank DESC"
end
if params[:category]
@category = Category.find_by_permalink!(params[:category])
@page_title << @category.name
@query.category_id_is(@category.id)
end
if params[:localization]
@localization = Localization.find_by_permalink!(params[:localization])
@page_title << @localization.name
@query.localization_id_is(@localization.id)
end
if params[:framework]
@framework = Framework.find_by_permalink!(params[:framework])
@page_title << @framework.name
options[:include] << :framework
@query.framework_id_is(@framework.id)
end
if params[:type_id]
@type_id = JOB_LABELS.index(params[:type_id]) || 0
@page_title << JOB_LABELS[@type_id]
@query.type_id_is(@type_id)
end
@jobs = @query.paginate(options)
respond_to do |format|
format.html # index.html.erb
format.rss
format.atom
end
end
def search
@page_title = ["Szukaj oferty"]
@search = Job.active.search(params[:search])
if params[:search]
@page_title = ["Znalezione oferty"]
@jobs = @search.paginate( :page => params[:page],
:per_page => 30,
:order => "created_at DESC, rank DESC" )
end
respond_to do |format|
format.html
format.rss { render :action => "index" }
format.atom { render :action => "index" }
end
end
# GET /jobs/1
# GET /jobs/1.xml
def show
@job = Job.find_by_permalink!(params[:id])
@job.visited_by(request.remote_ip)
@category = @job.category
respond_to do |format|
format.html # show.html.erb
end
end
# GET /jobs/new
# GET /jobs/new.xml
def new
@job = Job.new
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @job }
end
end
# POST /jobs
# POST /jobs.xml
def create
@job = Job.new(params[:job])
respond_to do |format|
if @job.save
flash[:notice] = 'Na twój e-mail zostaÅ wysÅany link którym opublikujesz ofertÄ.'
format.html { redirect_to(@job) }
format.xml { render :xml => @job, :status => :created, :location => @job }
else
format.html { render :action => "new" }
format.xml { render :xml => @job.errors, :status => :unprocessable_entity }
end
end
end
# GET /jobs/1/edit
def edit
@job = Job.find_by_permalink_and_token!(params[:id], params[:token])
render :action => "new"
end
# PUT /jobs/1
# PUT /jobs/1.xml
def update
@job = Job.find_by_permalink_and_token!(params[:id], params[:token])
respond_to do |format|
if @job.update_attributes(params[:job])
flash[:notice] = 'Zapisano zmiany w ofercie.'
format.html { redirect_to(@job) }
format.xml { head :ok }
else
format.html { render :action => "new" }
format.xml { render :xml => @job.errors, :status => :unprocessable_entity }
end
end
end
def publish
@job = Job.find_by_permalink_and_token!(params[:id], params[:token])
unless @job.published
@job.publish!
flash[:notice] = "Twoja oferta jest już widoczna!"
-
- spawn do
- tags = [@job.localization.name, @job.category.name]
- tags << @job.framework.name unless @job.framework.nil?
-
- if Rails.env == "production"
- MicroFeed.send :streams => :all,
- :msg => "[#{@job.company_name}] - #{@job.title}",
- :tags => tags,
- :link => seo_job_url(@job)
- end
- end
end
redirect_to @job
end
# DELETE /jobs/1
# DELETE /jobs/1.xml
def destroy
@job = Job.find_by_permalink_and_token!(params[:id], params[:token])
@job.destroy
flash[:notice] = "Oferta zostaÅa usuniÄta"
respond_to do |format|
format.html { redirect_to(jobs_url) }
format.xml { head :ok }
end
end
end
diff --git a/app/models/job.rb b/app/models/job.rb
index 8b5a287..879eb15 100644
--- a/app/models/job.rb
+++ b/app/models/job.rb
@@ -1,165 +1,174 @@
JOB_TYPES = ["zlecenie (konkretna usÅuga do wykonania)", "poszukiwanie wspóÅpracowników / oferta pracy", "wolontariat (praca za reklamy, bannery, itp. lub praca za darmo)", "staż/praktyka"]
JOB_LABELS = ["zlecenie", "etat", "wolontariat", "praktyka"]
JOB_ETAT = 1;
JOB_RANK_VALUES = {
:default => 0.3,
:price => 0.8,
:krs => 0.6,
:nip => 0.5,
:regon => 0.6,
:framework_id => 0.7,
:website => 0.3,
:apply_online => 0.2
}
class Job < ActiveRecord::Base
xss_terminate
has_permalink :title
named_scope :active, :conditions => ["((jobs.end_at >= ?) AND (jobs.published = ?))", Date.current, true]
named_scope :old, :conditions => ["jobs.end_at < ?", Date.current]
named_scope :has_text, lambda { |text| { :conditions => ["((jobs.title ILIKE ?) OR (jobs.description ILIKE ?))", "%#{text}%", "%#{text}%"] } }
validates_presence_of :title, :description, :email, :company_name, :localization_id, :category_id
validates_length_of :title, :within => 3..255
validates_length_of :description, :within => 10..5000
validates_inclusion_of :type_id, :in => 0..JOB_TYPES.size-1
validates_inclusion_of :dlugosc_trwania, :in => 1..60
validates_numericality_of :price_from,
:greater_than => 0,
:unless => Proc.new { |j| j.price_from.nil? }
validates_numericality_of :price_to,
:greater_than => 0,
:unless => Proc.new { |j| j.price_to.nil? }
validates_format_of :email, :with => Authlogic::Regex.email
validates_format_of :website, :with => /(^$)|(^(http|https):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(([0-9]{1,5})?\/.*)?$)/ix
validates_format_of :regon,
:with => /(^$)|(^[0-9]{7,14}$)/
validates_format_of :nip,
:with => /(^$)|(^\d{2,3}-\d{2,3}-\d{2,3}-\d{2,3}$)/
validates_format_of :krs,
:with => /(^$)|(^\d{10})$/
belongs_to :framework
belongs_to :localization
belongs_to :category
has_many :applicants, :dependent => :delete_all
has_many :visits, :dependent => :delete_all
attr_protected :rank, :permalink, :end_at, :token, :published
attr_accessor :framework_name, :localization_name
before_create :create_from_name, :generate_token
before_save :calculate_rank
after_create :send_notification
def self.find_grouped_by_type
return Job.active.count(:type_id, :group => "type_id")
end
def send_notification
JobMailer.deliver_job_posted(self)
end
def generate_token
alphanumerics = ('a'..'z').to_a.concat(('A'..'Z').to_a.concat(('0'..'9').to_a))
salt = alphanumerics.sort_by{rand}.to_s[0..1024]
self.token = Digest::SHA1.hexdigest("--#{salt}--#{self.id}--#{Date.current}--")
generate_token unless Job.find_by_token(self.token).nil?
end
def calculate_rank
self.rank = 1.0
self.rank += visits_count * 0.01 unless visits_count.nil?
[:regon, :nip, :krs, :framework_id, :website, :apply_online].each do |attribute|
val = send(attribute)
inc = JOB_RANK_VALUES[attribute] || JOB_RANK_VALUES[:default]
self.rank += inc unless (val.nil? || (val.class == String && val.empty?) || (val.class == TrueClass))
end
if widelki_zarobkowe?
self.rank += JOB_RANK_VALUES[:price]
price = price_from || price_to
if price >= 10_000 # ciekawe czy ktoÅ da tyle :P
self.rank += 0.8
elsif price >= 7000
self.rank += 0.7
elsif price >= 5000
self.rank += 0.6
elsif price >= 3000
self.rank += 0.3
elsif price < 2000
if self.type_id == JOB_ETAT
self.rank -= 0.6 # bo nikt za grosze nie chce pracowaÄ
else
self.rank += 0.3 # chyba że to biedny student
end
end
end
end
def widelki_zarobkowe?
((!self.price_from.nil? && self.price_from > 0) || (!self.price_to.nil? && self.price_to > 0))
end
def create_from_name
unless (self.framework_name.nil? || self.framework_name.blank?)
framework = Framework.name_like(self.framework_name).first
framework = Framework.create(:name => self.framework_name) if framework.nil?
self.framework = framework
end
unless (self.localization_name.nil? || self.localization_name.blank?)
localization = Localization.name_like(self.localization_name).first
localization = Localization.create(:name => self.localization_name) if localization.nil?
self.localization = localization
end
end
def dlugosc_trwania
date = created_at.nil? ? Date.current.to_date : created_at.to_date
return (read_attribute(:end_at) - date).to_i rescue 14
end
def dlugosc_trwania=(val)
date = created_at.nil? ? Date.current.to_date : created_at.to_date
write_attribute(:end_at, date+val.to_i.days)
end
def highlited?
self.rank >= 4.75
end
def publish!
self.published = true
save
+ spawn do
+ tags = [localization.name, category.name]
+ tags << framework.name unless framework.nil?
+
+ MicroFeed.send :streams => :all,
+ :msg => "[#{company_name}] - #{title}",
+ :tags => tags,
+ :link => seo_job_url(job, :host => "webpraca.net")
+ end
end
def visited_by(ip)
visit = visits.find_or_create_by_ip(IPAddr.new(ip).to_i)
visits_count += 1 if visit.new_record?
save
end
def to_param
permalink
end
end
diff --git a/lib/tasks/webpraca.rake b/lib/tasks/webpraca.rake
index f092735..69dffee 100644
--- a/lib/tasks/webpraca.rake
+++ b/lib/tasks/webpraca.rake
@@ -1,61 +1,67 @@
require 'highline/import'
def ask_for_password(message)
val = ask(message) {|q| q.echo = false}
if val.nil? || val.empty?
return ask_for_password(message)
else
return val
end
end
def ask(message)
puts "#{message}:"
val = STDIN.gets.chomp
if val.nil? || val.empty?
return ask(message)
else
return val
end
end
def render_errors(obj)
index = 0
obj.errors.each_full do |msg|
index += 1
puts "#{index}. #{msg}"
end
end
namespace :webpraca do
namespace :clear do
task :applicants => :environment do
Applicant.all.each(&:destroy)
end
task :visits => :environment do
Visit.all.each(&:destroy)
end
end
namespace :jobs do
task :remove_old => :environment do
Job.old.each(&:destroy)
end
+
+ task :publish_all => :environment do
+ Job.all.each do |job|
+ job.publish!
+ end
+ end
end
namespace :admin do
task :create => :environment do
puts "Creating new admin user"
user = User.new
user.email = ask("Enter E-Mail")
user.password = ask_for_password("Enter Password")
user.password_confirmation = ask_for_password("Enter password confirmation")
if user.save
puts "Created admin user!"
else
render_errors(user)
end
end
end
end
\ No newline at end of file
|
macbury/webpraca
|
719d802c4be3e38bd22236a80b31e4ba1b34cee0
|
Pluginy
|
diff --git a/vendor/plugins/MicroFeed/MIT-LICENSE b/vendor/plugins/MicroFeed/MIT-LICENSE
new file mode 100644
index 0000000..9d35220
--- /dev/null
+++ b/vendor/plugins/MicroFeed/MIT-LICENSE
@@ -0,0 +1,20 @@
+Copyright (c) 2010 Buras Arkadiusz
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+"Software"), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/vendor/plugins/MicroFeed/README b/vendor/plugins/MicroFeed/README
new file mode 100644
index 0000000..fa9e443
--- /dev/null
+++ b/vendor/plugins/MicroFeed/README
@@ -0,0 +1,41 @@
+MicroFeed
+=========
+
+Plugin do wysyÅania statusów do serwisów mikroblogowych(blip.pl, flaker.pl, spinacz.pl, pinger.pl)
+
+Konfiguracja
+=======
+
+Tworzymy plik micro_feed.yml w katalogu config:
+
+blip:
+ login: username
+ password: secret
+
+flaker:
+ login: username
+ password: secret
+
+pinger:
+ login: username
+ password: secret
+
+spinacz:
+ hash: 139c82e0679b64132f528fa71a9ee8d1
+
+Sposób użycia
+=======
+
+WysyÅanie do wszystkich serwisów
+MicroFeed.send :streams => :all, :msg => "Witaj Åwiecie"
+
+WysyÅanie do wybranych serwisów:
+MicroFeed.send :streams => [:blip, :flaker], :msg => "Witaj Åwiecie z flakera i blipa!"
+
+Otagowanie wpisów:
+MicroFeed.send :streams => :all, :msg => "Witaj Åwiecie", :tags => ["wiadomosc", "omg", "news"]
+
+WysyÅanie linku:
+MicroFeed.send :streams => :all, :msg => "Sprawdzcie ten link!", :link => "http://google.pl"
+
+Copyright (c) 2010 Buras Arkadiusz, released under the MIT license
diff --git a/vendor/plugins/MicroFeed/Rakefile b/vendor/plugins/MicroFeed/Rakefile
new file mode 100644
index 0000000..4cb028d
--- /dev/null
+++ b/vendor/plugins/MicroFeed/Rakefile
@@ -0,0 +1,23 @@
+require 'rake'
+require 'rake/testtask'
+require 'rake/rdoctask'
+
+desc 'Default: run unit tests.'
+task :default => :test
+
+desc 'Test the micro_feed plugin.'
+Rake::TestTask.new(:test) do |t|
+ t.libs << 'lib'
+ t.libs << 'test'
+ t.pattern = 'test/**/*_test.rb'
+ t.verbose = true
+end
+
+desc 'Generate documentation for the micro_feed plugin.'
+Rake::RDocTask.new(:rdoc) do |rdoc|
+ rdoc.rdoc_dir = 'rdoc'
+ rdoc.title = 'MicroFeed'
+ rdoc.options << '--line-numbers' << '--inline-source'
+ rdoc.rdoc_files.include('README')
+ rdoc.rdoc_files.include('lib/**/*.rb')
+end
diff --git a/vendor/plugins/MicroFeed/init.rb b/vendor/plugins/MicroFeed/init.rb
new file mode 100644
index 0000000..34f196c
--- /dev/null
+++ b/vendor/plugins/MicroFeed/init.rb
@@ -0,0 +1,2 @@
+# Include hook code here
+require "micro_feed"
diff --git a/vendor/plugins/MicroFeed/install.rb b/vendor/plugins/MicroFeed/install.rb
new file mode 100644
index 0000000..f7732d3
--- /dev/null
+++ b/vendor/plugins/MicroFeed/install.rb
@@ -0,0 +1 @@
+# Install hook code here
diff --git a/vendor/plugins/MicroFeed/lib/feeds/blip_feed.rb b/vendor/plugins/MicroFeed/lib/feeds/blip_feed.rb
new file mode 100644
index 0000000..95cbc62
--- /dev/null
+++ b/vendor/plugins/MicroFeed/lib/feeds/blip_feed.rb
@@ -0,0 +1,23 @@
+class BlipFeed
+ attr_accessor :user, :password
+
+ def setup(config={})
+ self.user = config['login']
+ self.password = config['password']
+ end
+
+ def send(options={})
+ url = URI.parse("http://api.blip.pl/updates")
+ req = Net::HTTP::Post.new(url.path)
+
+ req.basic_auth self.user, self.password
+
+ body = options[:msg]
+ body += " - " + options[:link] if options[:link]
+ body += " " + options[:tags].map { |tag| "##{tag}" }.join(', ') if options[:tags]
+
+ req.set_form_data({ 'body'=>body, 'User-Agent' => 'http://github.com/macbury/MicroFeed', 'Accept' => 'application/json', 'X-Blip-API' => '0.02'}, '&')
+ res = Net::HTTP.new(url.host, url.port).start {|http| http.request(req) }
+ end
+
+end
\ No newline at end of file
diff --git a/vendor/plugins/MicroFeed/lib/feeds/flaker_feed.rb b/vendor/plugins/MicroFeed/lib/feeds/flaker_feed.rb
new file mode 100644
index 0000000..ac91278
--- /dev/null
+++ b/vendor/plugins/MicroFeed/lib/feeds/flaker_feed.rb
@@ -0,0 +1,21 @@
+class FlakerFeed
+ attr_accessor :user, :password
+
+ def setup(config={})
+ self.user = config['login']
+ self.password = config['password']
+ end
+
+ def send(options={})
+ url = URI.parse("http://api.flaker.pl/api/type:submit")
+ req = Net::HTTP::Post.new(url.path)
+
+ req.basic_auth self.user, self.password
+
+ body = options[:msg]
+ body += " " + options[:tags].map { |tag| "##{tag}" }.join(', ') if options[:tags]
+
+ req.set_form_data({'text'=>body, 'link'=>options[:link]}, '&')
+ res = Net::HTTP.new(url.host, url.port).start {|http| http.request(req) }
+ end
+end
\ No newline at end of file
diff --git a/vendor/plugins/MicroFeed/lib/feeds/pinger_feed.rb b/vendor/plugins/MicroFeed/lib/feeds/pinger_feed.rb
new file mode 100644
index 0000000..9b2a7a4
--- /dev/null
+++ b/vendor/plugins/MicroFeed/lib/feeds/pinger_feed.rb
@@ -0,0 +1,21 @@
+class PingerFeed
+ attr_accessor :user, :password
+
+ def setup(config={})
+ self.user = config['login']
+ self.password = config['password']
+ end
+
+ def send(options={})
+ url = URI.parse("http://a.pinger.pl/auth_add_message.json")
+ req = Net::HTTP::Post.new(url.path)
+
+ req.basic_auth self.user, self.password
+
+ body = options[:msg]
+ body += " - " + options[:link] if options[:link]
+
+ req.set_form_data({'text'=>body, 'tags'=>options[:tags].join(', ')}, '&')
+ res = Net::HTTP.new(url.host, url.port).start {|http| http.request(req) }
+ end
+end
\ No newline at end of file
diff --git a/vendor/plugins/MicroFeed/lib/feeds/spinacz_feed.rb b/vendor/plugins/MicroFeed/lib/feeds/spinacz_feed.rb
new file mode 100644
index 0000000..c5edbd0
--- /dev/null
+++ b/vendor/plugins/MicroFeed/lib/feeds/spinacz_feed.rb
@@ -0,0 +1,20 @@
+class SpinaczFeed
+ attr_accessor :hash
+
+ def setup(config={})
+ self.hash = config['hash']
+ end
+
+ def send(options={})
+ url = URI.parse("http://spinacz.pl/feeds/add.json")
+ req = Net::HTTP::Post.new(url.path)
+
+
+ body = options[:msg]
+ body += " - " + options[:link] if options[:link]
+ body += " " + options[:tags].map { |tag| "##{tag}" }.join(', ') if options[:tags]
+
+ req.set_form_data({'content'=> body, 'HASH'=> self.hash}, '&')
+ res = Net::HTTP.new(url.host, url.port).start {|http| http.request(req) }
+ end
+end
\ No newline at end of file
diff --git a/vendor/plugins/MicroFeed/lib/micro_feed.rb b/vendor/plugins/MicroFeed/lib/micro_feed.rb
new file mode 100644
index 0000000..a9b217b
--- /dev/null
+++ b/vendor/plugins/MicroFeed/lib/micro_feed.rb
@@ -0,0 +1,43 @@
+require "net/http"
+require "uri"
+
+require "feeds/blip_feed"
+require "feeds/flaker_feed"
+require "feeds/spinacz_feed"
+require "feeds/pinger_feed"
+
+class MicroFeed
+ MICRO_FEED_CONFIG = YAML.load_file("#{RAILS_ROOT}/config/micro_feed.yml")
+ # WysyÅa wiadomoÅÄ do podanych serwisów mikroblogowych
+ # DostÄpne opcje:
+ # * +:streams+: serwisy do których ma dojÅÄ wiadomoÅÄ(:all, [:blip, :flaker], :blip)
+ # * +msg+: treÅÄ wiadomoÅci
+ # * +link+: link do strony
+ # * +tags+: tablica z tagami(np. ['sport', 'telewizja'])
+
+ def self.send(config={})
+ default = {
+ :streams => :all,
+ :msg => "Hello World!",
+ :link => nil,
+ :tags => nil
+ }.merge!(config)
+
+ available_streams = MICRO_FEED_CONFIG.map { |stream, config| stream.to_sym }
+
+ if default[:streams] == :all
+ send_to = available_streams
+ elsif default[:streams].class == Symbol
+ send_to = available_streams.include?(default[:streams].to_sym) ? [default[:streams]] : available_streams
+ else
+ send_to = default[:streams].reject { |stream| !available_streams.include?(stream.to_sym) }
+ end
+
+ send_to.each do |stream_name|
+ config = MICRO_FEED_CONFIG[stream_name.to_s]
+ sender = eval("#{stream_name.to_s.camelize}Feed").new
+ sender.setup(config)
+ sender.send(default)
+ end
+ end
+end
\ No newline at end of file
diff --git a/vendor/plugins/MicroFeed/micro_feed.yml b/vendor/plugins/MicroFeed/micro_feed.yml
new file mode 100644
index 0000000..92e6c20
--- /dev/null
+++ b/vendor/plugins/MicroFeed/micro_feed.yml
@@ -0,0 +1,14 @@
+blip:
+ login: username
+ password: secret
+
+flaker:
+ login: username
+ password: secret
+
+pinger:
+ login: username
+ password: secret
+
+spinacz:
+ hash: 139c82e0679b64132f528fa71a9ee8d1
\ No newline at end of file
diff --git a/vendor/plugins/MicroFeed/tasks/micro_feed_tasks.rake b/vendor/plugins/MicroFeed/tasks/micro_feed_tasks.rake
new file mode 100644
index 0000000..72b8716
--- /dev/null
+++ b/vendor/plugins/MicroFeed/tasks/micro_feed_tasks.rake
@@ -0,0 +1,4 @@
+# desc "Explaining what the task does"
+# task :micro_feed do
+# # Task goes here
+# end
diff --git a/vendor/plugins/MicroFeed/test/micro_feed_test.rb b/vendor/plugins/MicroFeed/test/micro_feed_test.rb
new file mode 100644
index 0000000..743788f
--- /dev/null
+++ b/vendor/plugins/MicroFeed/test/micro_feed_test.rb
@@ -0,0 +1,8 @@
+require 'test_helper'
+
+class MicroFeedTest < ActiveSupport::TestCase
+ # Replace this with your real tests.
+ test "the truth" do
+ assert true
+ end
+end
diff --git a/vendor/plugins/MicroFeed/test/test_helper.rb b/vendor/plugins/MicroFeed/test/test_helper.rb
new file mode 100644
index 0000000..cf148b8
--- /dev/null
+++ b/vendor/plugins/MicroFeed/test/test_helper.rb
@@ -0,0 +1,3 @@
+require 'rubygems'
+require 'active_support'
+require 'active_support/test_case'
\ No newline at end of file
diff --git a/vendor/plugins/MicroFeed/uninstall.rb b/vendor/plugins/MicroFeed/uninstall.rb
new file mode 100644
index 0000000..9738333
--- /dev/null
+++ b/vendor/plugins/MicroFeed/uninstall.rb
@@ -0,0 +1 @@
+# Uninstall hook code here
diff --git a/vendor/plugins/Stupid-Simple-Config/MIT-LICENSE b/vendor/plugins/Stupid-Simple-Config/MIT-LICENSE
new file mode 100644
index 0000000..ec4ddd4
--- /dev/null
+++ b/vendor/plugins/Stupid-Simple-Config/MIT-LICENSE
@@ -0,0 +1,20 @@
+Copyright (c) 2010 [name of plugin creator]
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+"Software"), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/vendor/plugins/Stupid-Simple-Config/README b/vendor/plugins/Stupid-Simple-Config/README
new file mode 100644
index 0000000..e9c661e
--- /dev/null
+++ b/vendor/plugins/Stupid-Simple-Config/README
@@ -0,0 +1,46 @@
+StupidSimpleConfig
+==================
+
+Stupid simple rails application configuration
+
+* simple YAML config files
+* config files support ERB
+
+Basic Usage
+=======
+
+You simply write a configuration file in YAML and save in your rails conifg directory. Notice you can use ERB.
+
+website
+ name: My website
+ tags: [ cool, website ]
+ author: Buras Arkadiusz
+ last_update: <%= Time.now %>
+
+Now create initializer and load your configuration:
+
+::WebSiteConfig = StupidSimpleConfig.new("website_config.yml")
+
+WebSiteConfig["website"]["name"] # => "My website"
+WebSiteConfig["website"]["tags"] # => ["cool", "webiste"]
+WebSiteConfig["webiste"]["last_update"] => Sun Jan 03 15:31:18 +0100 2010
+
+You can reload your configuration:
+
+WebSiteConfig.reload!
+
+And save changes:
+
+WebSiteConfig["website"]["name"] = "My website is cool"
+WebSiteConfig.save!
+
+or
+
+WebSiteConfig.update_attributes({
+ "website" => {
+ "name" => "My website is cool",
+ "tags" => ["cool", "website"]
+ }
+})
+
+Copyright (c) 2010 Buras Arkadiusz, released under the MIT license
diff --git a/vendor/plugins/Stupid-Simple-Config/Rakefile b/vendor/plugins/Stupid-Simple-Config/Rakefile
new file mode 100644
index 0000000..42025d8
--- /dev/null
+++ b/vendor/plugins/Stupid-Simple-Config/Rakefile
@@ -0,0 +1,23 @@
+require 'rake'
+require 'rake/testtask'
+require 'rake/rdoctask'
+
+desc 'Default: run unit tests.'
+task :default => :test
+
+desc 'Test the stupid_simple_config plugin.'
+Rake::TestTask.new(:test) do |t|
+ t.libs << 'lib'
+ t.libs << 'test'
+ t.pattern = 'test/**/*_test.rb'
+ t.verbose = true
+end
+
+desc 'Generate documentation for the stupid_simple_config plugin.'
+Rake::RDocTask.new(:rdoc) do |rdoc|
+ rdoc.rdoc_dir = 'rdoc'
+ rdoc.title = 'StupidSimpleConfig'
+ rdoc.options << '--line-numbers' << '--inline-source'
+ rdoc.rdoc_files.include('README')
+ rdoc.rdoc_files.include('lib/**/*.rb')
+end
diff --git a/vendor/plugins/Stupid-Simple-Config/init.rb b/vendor/plugins/Stupid-Simple-Config/init.rb
new file mode 100644
index 0000000..e0e52b5
--- /dev/null
+++ b/vendor/plugins/Stupid-Simple-Config/init.rb
@@ -0,0 +1 @@
+require "stupid_simple_config"
diff --git a/vendor/plugins/Stupid-Simple-Config/install.rb b/vendor/plugins/Stupid-Simple-Config/install.rb
new file mode 100644
index 0000000..f7732d3
--- /dev/null
+++ b/vendor/plugins/Stupid-Simple-Config/install.rb
@@ -0,0 +1 @@
+# Install hook code here
diff --git a/vendor/plugins/Stupid-Simple-Config/lib/stupid_simple_config.rb b/vendor/plugins/Stupid-Simple-Config/lib/stupid_simple_config.rb
new file mode 100644
index 0000000..3c35082
--- /dev/null
+++ b/vendor/plugins/Stupid-Simple-Config/lib/stupid_simple_config.rb
@@ -0,0 +1,25 @@
+require 'erb'
+
+class StupidSimpleConfig < Hash
+ attr_accessor :yaml_file
+
+ def initialize(yaml_file)
+ self.yaml_file = "#{RAILS_ROOT}/config/#{yaml_file}"
+ load!
+ end
+
+ def save!
+ File.open(self.yaml_file, "w") do |out|
+ YAML.dump(self, out)
+ end
+ end
+
+ def update_attributes(attributes={})
+ self.merge!(attributes)
+ self.save!
+ end
+
+ def load!
+ self.merge!(YAML::load(ERB.new(IO.read(self.yaml_file)).result))
+ end
+end
\ No newline at end of file
diff --git a/vendor/plugins/Stupid-Simple-Config/tasks/stupid_simple_config_tasks.rake b/vendor/plugins/Stupid-Simple-Config/tasks/stupid_simple_config_tasks.rake
new file mode 100644
index 0000000..9d3817e
--- /dev/null
+++ b/vendor/plugins/Stupid-Simple-Config/tasks/stupid_simple_config_tasks.rake
@@ -0,0 +1,4 @@
+# desc "Explaining what the task does"
+# task :stupid_simple_config do
+# # Task goes here
+# end
diff --git a/vendor/plugins/Stupid-Simple-Config/test/stupid_simple_config_test.rb b/vendor/plugins/Stupid-Simple-Config/test/stupid_simple_config_test.rb
new file mode 100644
index 0000000..5c4e504
--- /dev/null
+++ b/vendor/plugins/Stupid-Simple-Config/test/stupid_simple_config_test.rb
@@ -0,0 +1,8 @@
+require 'test_helper'
+
+class StupidSimpleConfigTest < ActiveSupport::TestCase
+ # Replace this with your real tests.
+ test "the truth" do
+ assert true
+ end
+end
diff --git a/vendor/plugins/Stupid-Simple-Config/test/test_helper.rb b/vendor/plugins/Stupid-Simple-Config/test/test_helper.rb
new file mode 100644
index 0000000..cf148b8
--- /dev/null
+++ b/vendor/plugins/Stupid-Simple-Config/test/test_helper.rb
@@ -0,0 +1,3 @@
+require 'rubygems'
+require 'active_support'
+require 'active_support/test_case'
\ No newline at end of file
diff --git a/vendor/plugins/Stupid-Simple-Config/uninstall.rb b/vendor/plugins/Stupid-Simple-Config/uninstall.rb
new file mode 100644
index 0000000..9738333
--- /dev/null
+++ b/vendor/plugins/Stupid-Simple-Config/uninstall.rb
@@ -0,0 +1 @@
+# Uninstall hook code here
|
macbury/webpraca
|
b4e73d5f231b74744ca9c997eee0926861d3ebb9
|
Lepsza nawigacja
|
diff --git a/app/controllers/admin/frameworks_controller.rb b/app/controllers/admin/frameworks_controller.rb
new file mode 100644
index 0000000..a591bb4
--- /dev/null
+++ b/app/controllers/admin/frameworks_controller.rb
@@ -0,0 +1,77 @@
+class Admin::FrameworksController < ApplicationController
+ before_filter :login_required
+ layout 'admin'
+ # GET /frameworks
+ # GET /frameworks.xml
+ def index
+ @frameworks = Framework.all
+
+ respond_to do |format|
+ format.html # index.html.erb
+ format.xml { render :xml => @frameworks }
+ end
+ end
+
+
+ # GET /frameworks/new
+ # GET /frameworks/new.xml
+ def new
+ @framework = Framework.new
+
+ respond_to do |format|
+ format.html # new.html.erb
+ format.xml { render :xml => @framework }
+ end
+ end
+
+ # GET /frameworks/1/edit
+ def edit
+ @framework = Framework.find(params[:id])
+ end
+
+ # POST /frameworks
+ # POST /frameworks.xml
+ def create
+ @framework = Framework.new(params[:framework])
+
+ respond_to do |format|
+ if @framework.save
+ flash[:notice] = 'Framework was successfully created.'
+ format.html { redirect_to(@framework) }
+ format.xml { render :xml => @framework, :status => :created, :location => @framework }
+ else
+ format.html { render :action => "new" }
+ format.xml { render :xml => @framework.errors, :status => :unprocessable_entity }
+ end
+ end
+ end
+
+ # PUT /frameworks/1
+ # PUT /frameworks/1.xml
+ def update
+ @framework = Framework.find(params[:id])
+
+ respond_to do |format|
+ if @framework.update_attributes(params[:framework])
+ flash[:notice] = 'Framework was successfully updated.'
+ format.html { redirect_to(@framework) }
+ format.xml { head :ok }
+ else
+ format.html { render :action => "edit" }
+ format.xml { render :xml => @framework.errors, :status => :unprocessable_entity }
+ end
+ end
+ end
+
+ # DELETE /frameworks/1
+ # DELETE /frameworks/1.xml
+ def destroy
+ @framework = Framework.find(params[:id])
+ @framework.destroy
+
+ respond_to do |format|
+ format.html { redirect_to(frameworks_url) }
+ format.xml { head :ok }
+ end
+ end
+end
diff --git a/app/controllers/jobs_controller.rb b/app/controllers/jobs_controller.rb
index 5659993..6e9272c 100644
--- a/app/controllers/jobs_controller.rb
+++ b/app/controllers/jobs_controller.rb
@@ -1,180 +1,185 @@
class JobsController < ApplicationController
validates_captcha :only => [:create, :new]
ads_pos :bottom
ads_pos :right, :except => [:home, :index, :search]
ads_pos :none, :only => [:home]
def home
@page_title = ['najpopularniejsze oferty', 'najnowsze oferty']
query = Job.active.search
@recent_jobs = query.all(:order => "created_at DESC", :limit => 10, :include => [:localization, :category])
@top_jobs = query.all(:order => "rank DESC, created_at DESC", :limit => 10, :include => [:localization, :category])
end
# GET /jobs
# GET /jobs.xml
def index
@query = Job.search
options = {
:page => params[:page],
:per_page => 25,
:order => "created_at DESC, rank DESC",
:include => [:localization, :category]
}
@query.active
- if params[:popular]
- options[:order] = "rank DESC, created_at DESC"
+ if params[:order] =~ /najpopularniejsze/i
@page_title = ['Najpopularniejsze oferty pracy']
+ @order = :rank
+ options[:order] = "rank DESC, created_at DESC"
else
+ @order = :created_at
@page_title = ['Najnowsze oferty pracy']
+ options[:order] = "created_at DESC, rank DESC"
end
if params[:category]
@category = Category.find_by_permalink!(params[:category])
@page_title << @category.name
@query.category_id_is(@category.id)
end
if params[:localization]
@localization = Localization.find_by_permalink!(params[:localization])
@page_title << @localization.name
@query.localization_id_is(@localization.id)
end
if params[:framework]
@framework = Framework.find_by_permalink!(params[:framework])
@page_title << @framework.name
options[:include] << :framework
@query.framework_id_is(@framework.id)
end
if params[:type_id]
@type_id = JOB_LABELS.index(params[:type_id]) || 0
@page_title << JOB_LABELS[@type_id]
@query.type_id_is(@type_id)
end
@jobs = @query.paginate(options)
respond_to do |format|
format.html # index.html.erb
format.rss
format.atom
end
end
def search
@page_title = ["Szukaj oferty"]
@search = Job.active.search(params[:search])
if params[:search]
@page_title = ["Znalezione oferty"]
@jobs = @search.paginate( :page => params[:page],
:per_page => 30,
:order => "created_at DESC, rank DESC" )
end
respond_to do |format|
format.html
format.rss { render :action => "index" }
format.atom { render :action => "index" }
end
end
# GET /jobs/1
# GET /jobs/1.xml
def show
@job = Job.find_by_permalink!(params[:id])
@job.visited_by(request.remote_ip)
@category = @job.category
respond_to do |format|
format.html # show.html.erb
end
end
# GET /jobs/new
# GET /jobs/new.xml
def new
@job = Job.new
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @job }
end
end
# POST /jobs
# POST /jobs.xml
def create
@job = Job.new(params[:job])
respond_to do |format|
if @job.save
flash[:notice] = 'Na twój e-mail zostaÅ wysÅany link którym opublikujesz ofertÄ.'
format.html { redirect_to(@job) }
format.xml { render :xml => @job, :status => :created, :location => @job }
else
format.html { render :action => "new" }
format.xml { render :xml => @job.errors, :status => :unprocessable_entity }
end
end
end
# GET /jobs/1/edit
def edit
@job = Job.find_by_permalink_and_token!(params[:id], params[:token])
render :action => "new"
end
# PUT /jobs/1
# PUT /jobs/1.xml
def update
@job = Job.find_by_permalink_and_token!(params[:id], params[:token])
respond_to do |format|
if @job.update_attributes(params[:job])
flash[:notice] = 'Zapisano zmiany w ofercie.'
format.html { redirect_to(@job) }
format.xml { head :ok }
else
format.html { render :action => "new" }
format.xml { render :xml => @job.errors, :status => :unprocessable_entity }
end
end
end
def publish
@job = Job.find_by_permalink_and_token!(params[:id], params[:token])
unless @job.published
@job.publish!
flash[:notice] = "Twoja oferta jest już widoczna!"
spawn do
tags = [@job.localization.name, @job.category.name]
tags << @job.framework.name unless @job.framework.nil?
- MicroFeed.send :streams => :all,
- :msg => "[#{@job.company_name}] - #{@job.title}",
- :tags => tags,
- :link => seo_job_url(@job)
+ if Rails.env == "production"
+ MicroFeed.send :streams => :all,
+ :msg => "[#{@job.company_name}] - #{@job.title}",
+ :tags => tags,
+ :link => seo_job_url(@job)
+ end
end
end
redirect_to @job
end
# DELETE /jobs/1
# DELETE /jobs/1.xml
def destroy
@job = Job.find_by_permalink_and_token!(params[:id], params[:token])
@job.destroy
flash[:notice] = "Oferta zostaÅa usuniÄta"
respond_to do |format|
format.html { redirect_to(jobs_url) }
format.xml { head :ok }
end
end
end
diff --git a/app/stylesheets/ui.less b/app/stylesheets/ui.less
index f0e224b..3515b7a 100644
--- a/app/stylesheets/ui.less
+++ b/app/stylesheets/ui.less
@@ -1,597 +1,600 @@
/* Defaults */
@text_color: #393733;
@link_color: #31627E;
@hover_color: #FF5917;
/* Global */
body {
margin: 0;
padding: 0;
font: 12px Arial;
color: @text_color;
overflow: auto;
background: #76787B url('/images/bkg.png') repeat-x top;
}
h1, h2, h3, h4 { margin: 0 0 5px 0; }
a { color: @link_color; cursor: pointer; outline: none !important; text-decoration: none; }
a:hover, a:focus { color: @hover_color; }
a img { border: 0; }
/* Table */
table { border-collapse: collapse; width: 100%; }
td, th {
font-size:11px;
border-bottom:1px solid #eee;
padding:5px;
}
th { text-align:left; font-size:12px; }
thead th { font-weight:bold; color:#666; padding:2px 5px; font-size:11px; background:#e1e1e1 url(/images/nav-bg.gif) top left repeat-x; border-left:1px solid #ddd; border-bottom:1px solid #ddd; }
thead th:first-child { border-left:none !important; }
thead th.optional { font-weight:normal !important; }
tr.alt { background:#f6f6f6; }
/* IDS */
.prices input[type="text"] { width: 50px !important; text-align: right; }
#job_captcha_image, #applicant_captcha_image, .captcha img { margin-bottom: -22px !important; margin-right: 10px !important; }
#job_captcha_solution, #applicant_captcha_solution, .captcha input { width: 200px !important; }
#AdTaily_Widget_Container { padding-top: 5px; }
/* Custom class */
.rounded_corners (@radius: 5px) {
-moz-border-radius: @radius;
-webkit-border-radius: @radius;
border-radius: @radius;
-o-border-radius: @radius;
}
.rounded_corner_top_left(@radius: 5px) { -moz-border-radius-topleft: @radius; -webkit-border-top-left-radius: @radius; border-top-left-radius: @radius; }
.rounded_corner_top_right(@radius: 5px) { -moz-border-radius-topright: @radius; -webkit-border-top-right-radius: @radius; border-top-right-radius: @radius; }
.rounded_corner_bottom_left(@radius: 5px) { -moz-border-radius-bottomleft: @radius; -webkit-border-bottom-left-radius: @radius; border-bottom-left-radius: @radius; }
.rounded_corner_bottom_right(@radius: 5px) { -moz-border-radius-bottomright: @radius; -webkit-border-bottom-right-radius: @radius; border-bottom-right-radius: @radius; }
.reset { margin: 0; padding: 0; list-style: none; }
.text_center { text-align: center; }
.text_right { text-align: right; }
.clear { clear: both; }
.info { text-align: center; color: #ddd; font-size: 28px; font-weight: bold; }
.loader { background: transparent url('/images/ajax.gif') no-repeat center center; height: 20px; display: none; }
.right { float: right; }
.left { float: left; }
/* Flash */
.flash {
background-color: #A4E1A2;
border: 1px solid #DDE3D7;
text-shadow: #C0FDE3 0px 1px 0px;
.rounded_corners(5px);
color: #094808;
margin-top: 10px;
opacity: 0.8;
padding: 10px;
}
.flash.error {
background-color: #AF2B2B;
color: #fff;
border: 1px solid #DA3536;
text-shadow: #000 0px 1px 0px;
}
.flash:hover { opacity: 1.0; }
.flash .dismiss {
background: transparent url('/images/close.png') no-repeat !important;
float: right;
height: 10px;
width: 9px;
text-indent: 9999px;
overflow: hidden;
}
.flash p {
font-weight: normal;
line-height: 15px;
margin: 0px;
}
.flash_error {
background: #AF2B2B url('../images/icon-error.png') 20px center no-repeat;
color: #fff;
border: 1px solid #DA3536;
text-shadow: #000 0px 1px 0px;
}
/* Buttons */
.buttons { margin: 0 5px; }
.button {
background: #DDD url('../images/button.png') repeat-x 0px 0px;
border: 1px solid #999;
display: inline-block;
outline: none;
-webkit-box-shadow: rgba(0, 0, 0, 0.117188) 0px 1px 0px;
}
.button > input[type="button"], .button > input[type="submit"], .button > a {
border: none;
line-height: 23px;
height: 23px;
padding: 0 10px;
color: #333 !important;
font-weight: bold;
text-decoration: none;
font-size: 11px;
cursor: default;
background: transparent;
}
.button:active {
background-color: #ddd;
background-image: none;
}
.button img {
margin-bottom: -4px;
margin-right: 5px;
width: 16px;
height: 16px;
}
.button.right { float: right; }
/* TextFields */
select { min-width: 150px; }
input[type="text"], input[type="password"], textarea {
padding: 4px 3px !important;
border: 1px solid #96A6C5;
color: #000;
}
textarea { height: 200px; min-height: 200px; }
input[type="text"]:focus, input[type="password"]:focus, textarea:focus {
background-color: #e6f7ff;
border-bottom: 1px solid #7FAEFF;
border-right: 1px solid #7FAEFF;
border-left: 1px solid #4478A8;
border-top: 1px solid #4478A8;
}
form > fieldset {
border: 2px solid #ddd !important;
.rounded_corners;
padding: 10px 15px !important;
margin: 10px 5px !important;
}
form > fieldset > legend {
font-weight: bold;
padding: 0 15px 0px 0 !important;
margin-left: -22px !important;
background: #fff;
font-size: 16px;
color: #333 !important;
}
/* Wrapper */
@wrapper_width: 900px;
.wrapper {
margin: 0px auto;
width: @wrapper_width;
min-height: 500px;
}
/* Header */
@header_height: 80px;
.wrapper > .header {
height: @header_height;
width: @wrapper_width;
position:relative;
}
@logo_width: 347px;
@menu_color: #35373A;
@header_link_color: #D8D8D9;
.header > h1#logo {
left: 8px;
position: absolute;
top: 10px;
width: @logo_width;
}
.header > h1#logo a { color: #fff; font: 28px "Trebuchet MS"; font-weight: bold; }
.header > h1#logo a:hover { background: transparent; }
.header > ul.categories {
.reset;
position: absolute;
bottom: 5px;
left: 0px;
+ width: @content_width;
}
.header > ul.categories li {
display:inline;
margin-left: 3px;
}
+.header > ul.categories li.right { float: right; margin-left: 6px; }
+
.header > ul.categories li > a {
padding: 5px 10px;
margin-top: 5px;
font-size: 13px;
color: @header_link_color;
.rounded_corner_top_left;
.rounded_corner_top_right;
background: @menu_color;
}
.header > ul.categories li > a:hover { background: #5d5f62; }
.header > ul.categories li > .selected { color: #fff; background: #2A2B2D !important; }
.header > ul.menu {
.reset;
.rounded_corner_bottom_left;
.rounded_corner_bottom_right;
position:absolute;
top: 0px;
padding: 5px 10px;
right: 0px;
background: @menu_color;
}
.header > ul.menu li{
display:inline;
margin-left: 3px;
padding-left: 6px;
border-left: 1px dotted #212326;
background-color:transparent;
font-size: 10px;
font-weight: bold;
color: @header_link_color;
}
.header > ul.menu li a { color: @header_link_color; }
.header > ul.menu li a:hover { color: #fff; background: transparent; }
.header > ul.menu li:first-child { border: 0; margin-left: 0; padding-left: 0; }
/* Sidebar */
@sidebar_width: 200px;
.wrapper > .sidebar {
float: right;
width: @sidebar_width;
margin-top: 20px;
}
.wrapper > .sidebar ul { .reset; }
/* content */
@content_padding_right: 10px;
@content_width: @wrapper_width - @sidebar_width - @content_padding_right;
.wrapper > .content {
float: left;
width: @content_width;
padding-right: @content_padding_right;
margin-top: 20px;
}
/*.wrapper > .content p { margin: 0 0 10px 0; padding: 0;} */
/* Box */
.box {
margin-bottom: 10px;
padding: 6px;
background: #9C9C9C;
.rounded_corners(5px);
}
@box_div_border_radius: 4px;
.box > div {
background: #fff;
margin-bottom: 10px;
padding-bottom: 5px;
.rounded_corners(@box_div_border_radius);
}
.box > div:last-child { margin-bottom: 0; }
@title_height: 39px;
@sidebar_title_height: 29px;
.box .title {
height: @title_height;
.rounded_corner_top_right(@box_div_border_radius);
.rounded_corner_top_left(@box_div_border_radius);
display: block;
background: #fff url('/images/title-header.png') repeat-x bottom;
border-bottom: 1px solid #F1EFBD;
}
.box .title > h2, .box .title > h3 {
margin: 0;
padding: 1px 10px 0 10px;
line-height: @title_height - 1px;
font-weight: normal;
font-size: 18px;
color: #656666;
}
.box .title > h3 {
font-size: 16px;
line-height: @sidebar_title_height - 1px;
}
.box .title > h2 > span, .box .title > h3 > span { color: #8E8F8F; }
.box > div form { margin: 5px !important; }
.box p {
margin: 10px;
}
.sidebar .box .title, .box .title.mini {
height: @sidebar_title_height;
}
/* list */
.list {
.reset;
.clear;
}
.list > li { clear: both; padding: 5px; }
.list > .alt { background:#f6f6f6; }
.list > li > .ranked { font-weight: bold; }
.list > li .handle { cursor: move; margin: 3px 5px 0 5px; }
.list > li > .badge {
float: right;
min-width: 18px;
padding: 2px 3px;
font-weight: bold;
font-size: 10px;
color: #fff;
background: #8798BB;
.rounded_corners(7px);
text-align: center;
}
.list > li > .rank {
.rounded_corners(2px);
text-align: center;
min-width: 18px;
padding: 2px 3px;
font-weight: bold;
font-size: 9px;
float: right;
background: #FFFF98;
border: 1px solid #E2E28C;
margin-top: -1px;
}
.list > li > .date {
font-size: 11px;
font-style: italic;
color: #7C7C7C;
}
/* more button */
.more {
background: #fff url('/images/more.gif') 0% 0% repeat-x;
border: 1px solid #DDD;
border-bottom: 1px solid #AAA;
border-right: 1px solid #AAA;
display: block;
font-size: 14px;
font-weight: bold;
color: inherit;
height: 22px;
line-height: 1.5em;
padding: 6px 0px;
text-align: center;
text-shadow: #fff 1px 1px 1px;
.rounded_corners(6px);
}
.more:hover {
background-position: 0% -78px;
border: 1px solid #BBB;
color: inherit;
}
.more:active {
background-position: 0% -38px;
color: #666;
}
/* Etykiety */
.etykieta {
display: block;
float: left;
font-size: 9px;
margin-right: 5px;
margin-top: -1px;
text-align: center;
width: 60px;
.rounded_corners(2px);
padding: 2px 3px;
color: #fff;
}
.etykieta:hover { color: #fff; }
.etykieta.zdalnie {
background: #357CCB;
border: 1px solid #2C6AB0;
}
.etykieta.zlecenie {
background: #F8854E;
border: 1px solid #D27244;
}
.etykieta.etat {
background: #408000;
border: 1px solid #366E01;
}
.etykieta.praktyka {
background: #FF6;
border: 1px solid #E2E25C;
color: #31627E;
}
.praktyka:hover { color: #31627E; }
.etykieta.wolontariat {
background: #D6D6D6;
border: 1px solid #B1B1B1;
color: #31627E;
}
.wolontariat:hover { color: #31627E; }
/* Pagination */
.pagination { background: white; margin: 5px 5px 0 5px; }
.pagination a, .pagination span {
padding: .2em .5em;
display: block;
float: left;
margin-right: 1px;
}
.pagination span.disabled {
color: #999;
border: 1px solid #DDD;
}
.pagination span.current {
font-weight: bold;
background: #2E6AB1;
color: white;
border: 1px solid #2E6AB1;
}
.pagination a {
text-decoration: none;
color: #105CB6;
border: 1px solid #9AAFE5;
}
.pagination a:hover, .pagination a:focus {
color: #003;
border-color: #003;
background-color: transparent;
}
.pagination .page_info {
background: #2E6AB1;
color: white;
padding: .4em .6em;
width: 22em;
margin-bottom: .3em;
text-align: center;
}
.pagination .page_info b {
color: #003;
background: #6aa6ed;
padding: .1em .25em;
}
.pagination:after {
content: ".";
display: block;
height: 0;
clear: both;
visibility: hidden;
}
* html .pagination { height: 1%; }
*:first-child+html .pagination { overflow: hidden; }
/* describe list */
@dt_width: 180px;
@dt_padding_right: 10px;
@dl_padding_left: 10px;
dl {
padding: 0px;
margin: 10px 0 0 0;
display: block;
}
dl dt {
width: @dt_width;
text-align: right;
color: #888;
float: left;
display: block;
padding: 0 @dt_padding_right 6px 0;
margin: 0;
}
dl dd {
width: @content_width - @dt_width - @dt_padding_right - @dl_padding_left - 15px;
border-left: 1px solid #ccc;
float: left;
padding: 0 0 10px @dl_padding_left;
margin: 0;
}
dl dd:last-child { padding-bottom: 0px; }
dl dd ul {
padding: 5px 0 0 20px;
margin: 0;
}
/* feed icon */
.feed {
float: right;
margin-top: 5px;
margin-right: -3px;
}
/* footer */
.footer {
margin: 10px auto;
width: @wrapper_width;
color: #D8D8D9;
}
.footer strong a { color: #fff; }
.footer a { color: #D8D8D9; }
.footer a:hover { color: #fff; }
.footer .right { margin-top: 3px; }
\ No newline at end of file
diff --git a/app/views/admin/frameworks/edit.html.erb b/app/views/admin/frameworks/edit.html.erb
new file mode 100644
index 0000000..b02ea99
--- /dev/null
+++ b/app/views/admin/frameworks/edit.html.erb
@@ -0,0 +1,16 @@
+<h1>Editing framework</h1>
+
+<% form_for(@framework) do |f| %>
+ <%= f.error_messages %>
+
+ <p>
+ <%= f.label :name %><br />
+ <%= f.text_field :name %>
+ </p>
+ <p>
+ <%= f.submit 'Update' %>
+ </p>
+<% end %>
+
+<%= link_to 'Show', @framework %> |
+<%= link_to 'Back', frameworks_path %>
\ No newline at end of file
diff --git a/app/views/admin/frameworks/index.html.erb b/app/views/admin/frameworks/index.html.erb
new file mode 100644
index 0000000..b455446
--- /dev/null
+++ b/app/views/admin/frameworks/index.html.erb
@@ -0,0 +1,20 @@
+<h1>Listing frameworks</h1>
+
+<table>
+ <tr>
+ <th>Name</th>
+ </tr>
+
+<% @frameworks.each do |framework| %>
+ <tr>
+ <td><%=h framework.name %></td>
+ <td><%= link_to 'Show', framework %></td>
+ <td><%= link_to 'Edit', edit_framework_path(framework) %></td>
+ <td><%= link_to 'Destroy', framework, :confirm => 'Are you sure?', :method => :delete %></td>
+ </tr>
+<% end %>
+</table>
+
+<br />
+
+<%= link_to 'New framework', new_framework_path %>
\ No newline at end of file
diff --git a/app/views/admin/frameworks/new.html.erb b/app/views/admin/frameworks/new.html.erb
new file mode 100644
index 0000000..ca3ec16
--- /dev/null
+++ b/app/views/admin/frameworks/new.html.erb
@@ -0,0 +1,15 @@
+<h1>New framework</h1>
+
+<% form_for(@framework) do |f| %>
+ <%= f.error_messages %>
+
+ <p>
+ <%= f.label :name %><br />
+ <%= f.text_field :name %>
+ </p>
+ <p>
+ <%= f.submit 'Create' %>
+ </p>
+<% end %>
+
+<%= link_to 'Back', frameworks_path %>
\ No newline at end of file
diff --git a/app/views/admin/frameworks/show.html.erb b/app/views/admin/frameworks/show.html.erb
new file mode 100644
index 0000000..aeab4ee
--- /dev/null
+++ b/app/views/admin/frameworks/show.html.erb
@@ -0,0 +1,8 @@
+<p>
+ <b>Name:</b>
+ <%=h @framework.name %>
+</p>
+
+
+<%= link_to 'Edit', edit_framework_path(@framework) %> |
+<%= link_to 'Back', frameworks_path %>
\ No newline at end of file
diff --git a/app/views/jobs/home.html.erb b/app/views/jobs/home.html.erb
index 92b3fb8..7732b93 100644
--- a/app/views/jobs/home.html.erb
+++ b/app/views/jobs/home.html.erb
@@ -1,26 +1,32 @@
<% content_for :sidebar do %>
<%= render :partial => "/jobs/sidebar" %>
<% end %>
<div class="box">
<div>
<div class="title">
- <h2><span>najpopularniejsze</span> oferty</h2>
+ <h2>
+ <%= link_to image_tag('feed.png'), jobs_path(stripped_params(:format => :rss, :order => "najpopularniejsze")), :title => "najpopularniejsze", :class => "feed" %>
+ <span>najpopularniejsze</span> oferty
+ </h2>
</div>
<%= render :partial => "jobs", :object => @top_jobs %>
</div>
<div>
<%= render :partial => "/shared/ads" %>
</div>
<div>
<div class="title">
- <h2><span>najnowsze</span> oferty</h2>
+ <h2>
+ <%= link_to image_tag('feed.png'), jobs_url(stripped_params(:format => :rss)), :title => "najnowsze oferty", :class => "feed" %>
+ <span>najnowsze</span> oferty
+ </h2>
</div>
<%= render :partial => "jobs", :object => @recent_jobs %>
</div>
<%= link_to 'pokaż wiÄcej ofert', jobs_path, :class => "more" %>
</div>
\ No newline at end of file
diff --git a/app/views/jobs/new.html.erb b/app/views/jobs/new.html.erb
index f64c51e..f627583 100644
--- a/app/views/jobs/new.html.erb
+++ b/app/views/jobs/new.html.erb
@@ -1,20 +1,20 @@
<% title @job.new_record? ? "Nowa oferta" : ["Edycja oferty", @job.title] %>
<div class="box">
<div>
<div class="title">
<h2><%= @job.new_record? ? "Nowa oferta" : "Edycja oferty" %></h2>
</div>
<% semantic_form_for(@job) do |f| %>
<%= render :partial => "form", :object => f %>
<div class="buttons">
<div class="button">
- <%= f.submit @job.new_record? ? "Dodaj oferte" : "Zapisz zmiany" %>
+ <%= f.submit @job.new_record? ? "Zgadzam siÄ z regulaminem i chcÄ dodaÄ ofertÄ" : "Zapisz zmiany" %>
</div>
<% unless @job.new_record? %>
, <%= link_to "usuÅ", @job, :method => :delete, :confirm => "Czy na pewno chcesz usunÄ
Ä ofertÄ?" %>
<% end %>
albo <%= link_to 'anuluj', jobs_path %>
</div>
<% end %>
</div>
</div>
\ No newline at end of file
diff --git a/app/views/layouts/admin.html.erb b/app/views/layouts/admin.html.erb
index 91ff47d..69807fa 100644
--- a/app/views/layouts/admin.html.erb
+++ b/app/views/layouts/admin.html.erb
@@ -1,47 +1,48 @@
<!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" lang="pl">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<%= display_meta_tags :site => WebSiteConfig['website']['name'] %>
<%= javascript_tag "window._token = '#{form_authenticity_token}'" %>
<%= javascript_include_merged :base %>
<%= javascript_include_merged :admin %>
<%= stylesheet_link_merged :base %>
</head>
<body>
<div class="wrapper">
<div class="header">
<h1 id="logo"><%= link_to "Panel administracyjny", admin_path %></h1>
<ul class="categories">
<li><%= link_to "Strony", admin_pages_path, :class => params[:controller] == "admin/pages" ? "selected" : "normal" %></li>
<li><%= link_to "Kategorie", admin_categories_path, :class => params[:controller] == "admin/categories" ? "selected" : "normal" %></li>
<li><%= link_to "Oferty", admin_jobs_path, :class => params[:controller] == "admin/jobs" ? "selected" : "normal" %></li>
+ <li><%= link_to "Frameworki", admin_frameworks_path, :class => params[:controller] == "admin/frameworks" ? "selected" : "normal" %></li>
<li><%= link_to "Ustawienia", admin_config_path, :class => params[:controller] == "admin/configs" ? "selected" : "normal" %></li>
</ul>
<ul class="menu">
<li>Witaj <strong><%= self.current_user.email %></strong>!</li>
<li><%= link_to "Wyloguj siÄ", logout_path %></li>
</ul>
</div>
<%- flash.each do |name, msg| -%>
<div class="<%= "flash #{name}" %>">
<a href="#" class="dismiss">X</a>
<p><%= msg %></p>
</div>
<%- end -%>
<div class="sidebar">
<%= yield :sidebar %>
</div>
<div class="content">
<%= yield %>
</div>
<div class="clear"></div>
</div>
<%= render :partial => "/shared/footer" %>
</body>
</html>
\ No newline at end of file
diff --git a/app/views/layouts/application.html.erb b/app/views/layouts/application.html.erb
index 99c654d..4666f0f 100644
--- a/app/views/layouts/application.html.erb
+++ b/app/views/layouts/application.html.erb
@@ -1,74 +1,79 @@
<!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" lang="pl">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<%= display_meta_tags :site => WebSiteConfig['website']['name'] %>
<meta name="viewport" content="width=900" />
<%= rss_link("RSS", jobs_url(:format => :rss)) %>
<%= rss_link("ATOM", jobs_url(:format => :atom)) %>
<%= javascript_tag "window._token = '#{form_authenticity_token}'" %>
<%= javascript_include_merged :base %>
<%= stylesheet_link_merged :base %>
</head>
<body>
<div class="wrapper">
<div class="header">
<h1 id="logo"><%= link_to WebSiteConfig['website']['name'], root_path %></h1>
<ul class="categories">
+ <li class="right">
+ <%= link_to "Najpopularniejsze", seo_jobs_path(:order => 'najpopularniejsze', :category => params[:category]), :class => (!@order.nil? && @order == :rank) ? "selected" : "normal" %>
+ </li>
+ <li class="right">
+ <%= link_to "Najnowsze", seo_jobs_path(:order => 'najnowsze', :category => params[:category] ), :class => (!@order.nil? && @order == :created_at) ? "selected" : "normal" %>
+ </li>
<% for category in Category.all(:order => "position") %>
<li>
- <%= link_to category.name, job_category_path(category), :class => (!@category.nil? && @category.id == category.id) ? "selected" : "normal" %>
+ <%= link_to category.name, seo_jobs_path(:order => params[:order], :category => category.permalink), :class => (!@category.nil? && @category.id == category.id) ? "selected" : "normal" %>
</li>
<% end %>
</ul>
<ul class="menu">
<li><%= link_to "Strona gÅówna", root_path %></li>
- <li><%= link_to "Najnowsze oferty", jobs_path %></li>
- <li><%= link_to "Najpopularniejsze oferty", popular_jobs_path %></li>
<li><%= link_to "Szukaj", search_jobs_path %></li>
- <li><%= link_to "O nas", "/strona/o-nas/" %></li>
+ <li><%= link_to "Informacje", "/strona/informacje/" %></li>
+ <li><%= link_to "Regulamin", "/strona/regulamin/" %></li>
<li><%= link_to "Kontakt", contact_path %></li>
</ul>
</div>
<%- flash.each do |name, msg| -%>
<div class="<%= "flash #{name}" %>">
<a href="#" class="dismiss">X</a>
<p><%= msg %></p>
</div>
<%- end -%>
<div class="sidebar">
<div class="box">
- <%= link_to "Dodaj OfertÄ!", new_job_path, :id => "add_job", :class => "more" %>
+ <%= link_to "Dodaj ofertÄ za DARMO!", new_job_path, :id => "add_job", :class => "more" %>
</div>
<%= yield :sidebar %>
<% if @ads_pos == :right %>
<div class="box">
<div>
<%= render :partial => "/shared/ads" %>
</div>
</div>
<% end %>
</div>
<div class="content">
<%= yield %>
<% if @ads_pos == :bottom %>
<div class="box">
<div>
<%= render :partial => "/shared/ads" %>
</div>
</div>
<% end %>
</div>
<div class="clear"></div>
</div>
<%= render :partial => "/shared/footer" %>
<%= WebSiteConfig['js']['google_analytics'] %>
</body>
</html>
\ No newline at end of file
diff --git a/app/views/shared/_footer.html.erb b/app/views/shared/_footer.html.erb
index 82a3ce0..394cb5d 100644
--- a/app/views/shared/_footer.html.erb
+++ b/app/views/shared/_footer.html.erb
@@ -1,11 +1,12 @@
<div class="footer">
<span class="right">
<%= link_to "Strona gÅówna", root_path %> |
<%= link_to "Oferty", jobs_path %> |
<%= link_to "Szukaj", search_jobs_path %> |
- <%= link_to "O nas", "/strona/o-nas/" %> |
+ <%= link_to "Informacje", "/strona/informacje/" %> |
+ <%= link_to "Regulamin", "/strona/regulamin/" %> |
<%= link_to "Kontakt", contact_path %> |
<%= link_to "GitHub", "http://github.com/macbury/webpraca" %>
</span>
<strong><%= link_to WebSiteConfig['website']['name'], root_path %></strong> <sup>BETA</sup> © <%= Date.current.year %>.
</div>
\ No newline at end of file
diff --git a/config/routes.rb b/config/routes.rb
index cd8bf4a..7fe7c52 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -1,80 +1,86 @@
ActionController::Routing::Routes.draw do |map|
map.new_contact '/contact/new', :controller => 'contact', :action => 'new', :conditions => { :method => :get }
map.contact '/contact', :controller => 'contact', :action => 'new', :conditions => { :method => :get }
map.contact '/contact', :controller => 'contact', :action => 'create', :conditions => { :method => :post }
map.seo_page '/strona/:id/', :controller => 'admin/pages', :action => 'show'
map.with_options :controller => 'jobs', :action => 'index' do |job|
+ job.with_options :category => nil, :page => 1, :order => "najnowsze", :requirements => { :order => /(najnowsze|najpopularniejsze)/, :page => /\d/ } do |seo|
+ seo.connect '/oferty/:page'
+ seo.connect '/oferty/:order'
+ seo.connect '/oferty/:order/:page'
+ seo.seo_jobs '/oferty/:order/:category/:page'
+ end
+
job.connect '/lokalizacja/:localization/:page'
job.localization '/lokalizacja/:localization'
job.connect '/framework/:framework/:page'
job.framework '/framework/:framework'
job.connect '/typ/:type_id/:page'
job.job_type '/typ/:type_id'
job.connect '/kategoria/:category/:page'
job.job_category '/kategoria/:category'
- job.connect '/najpopularniejsze/:page', :popular => true
- job.popular_jobs '/najpopularniejsze', :popular => true
end
map.resources :jobs, :member => { :publish => :get, :destroy => :any }, :collection => { :search => :any } do |jobs|
jobs.resources :applicants, :member => { :download => :get }
end
map.resources :user_sessions
map.login '/login', :controller => 'user_sessions', :action => 'new'
map.logout '/logout', :controller => 'user_sessions', :action => 'destroy'
map.namespace :admin do |admin|
admin.config '/config', :controller => "configs", :action => "new"
admin.resources :pages
admin.resources :jobs
admin.resource :configs
+ admin.resources :frameworks
admin.resources :categories, :collection => { :reorder => :post }
end
map.admin '/admin', :controller => "admin/pages"
# The priority is based upon order of creation: first created -> highest priority.
# Sample of regular route:
# map.connect 'products/:id', :controller => 'catalog', :action => 'view'
# Keep in mind you can assign values other than :controller and :action
# Sample of named route:
# map.purchase 'products/:id/purchase', :controller => 'catalog', :action => 'purchase'
# This route can be invoked with purchase_url(:id => product.id)
# Sample resource route (maps HTTP verbs to controller actions automatically):
# map.resources :products
# Sample resource route with options:
# map.resources :products, :member => { :short => :get, :toggle => :post }, :collection => { :sold => :get }
# Sample resource route with sub-resources:
# map.resources :products, :has_many => [ :comments, :sales ], :has_one => :seller
# Sample resource route with more complex sub-resources
# map.resources :products do |products|
# products.resources :comments
# products.resources :sales, :collection => { :recent => :get }
# end
# Sample resource route within a namespace:
# map.namespace :admin do |admin|
# # Directs /admin/products/* to Admin::ProductsController (app/controllers/admin/products_controller.rb)
# admin.resources :products
# end
map.root :controller => "jobs", :action => "home"
map.seo_job '/:id', :controller => 'jobs', :action => 'show'
# You can have the root of your site routed with map.root -- just remember to delete public/index.html.
# See how all your routes lay out with "rake routes"
# Install the default routes as the lowest priority.
# Note: These default routes make all actions in every controller accessible via GET requests. You should
# consider removing or commenting them out if you're using named routes and resources.
map.connect ':controller/:action/:id'
map.connect ':controller/:action/:id.:format'
end
diff --git a/config/sitemap.rb b/config/sitemap.rb
index 4079f4c..4050c79 100644
--- a/config/sitemap.rb
+++ b/config/sitemap.rb
@@ -1,57 +1,56 @@
# Set the host name for URL creation
SitemapGenerator::Sitemap.default_host = "http://webpraca.net"
SitemapGenerator::Sitemap.add_links do |sitemap|
# Put links creation logic here.
#
# The root path '/' and sitemap index file are added automatically.
# Links are added to the Sitemap in the order they are specified.
#
# Usage: sitemap.add path, options
# (default options are used if you don't specify)
#
# Defaults: :priority => 0.5, :changefreq => 'weekly',
# :lastmod => Time.now, :host => default_host
# Examples:
# add '/articles'
sitemap.add jobs_path, :priority => 1.0, :changefreq => 'daily'
- sitemap.add popular_jobs_path
# add all individual articles
Job.active.each do |o|
sitemap.add seo_job_path(o), :lastmod => o.updated_at
end
Framework.all.each do |f|
latest_job = f.jobs.first(:order => "created_at DESC")
sitemap.add framework_path(f), :lastmod => latest_job.nil? ? f.created_at : latest_job.created_at
end
Localization.all.each do |l|
latest_job = l.jobs.first(:order => "created_at DESC")
sitemap.add localization_path(l), :lastmod => latest_job.nil? ? l.created_at : latest_job.created_at
end
Category.all.each do |c|
latest_job = c.jobs.first(:order => "created_at DESC")
sitemap.add job_category_path(c), :lastmod => latest_job.nil? ? c.created_at : latest_job.created_at
end
Page.all.each do |page|
sitemap.add seo_page_path(page), :lastmod => page.updated_at
end
end
# Including Sitemaps from Rails Engines.
#
# These Sitemaps should be almost identical to a regular Sitemap file except
# they needn't define their own SitemapGenerator::Sitemap.default_host since
# they will undoubtedly share the host name of the application they belong to.
#
# As an example, say we have a Rails Engine in vendor/plugins/cadability_client
# We can include its Sitemap here as follows:
#
# file = File.join(Rails.root, 'vendor/plugins/cadability_client/config/sitemap.rb')
# eval(open(file).read, binding, file)
\ No newline at end of file
diff --git a/db/schema.rb b/db/schema.rb
index 89a7c6d..88895c8 100644
--- a/db/schema.rb
+++ b/db/schema.rb
@@ -1,126 +1,132 @@
# This file is auto-generated from the current state of the database. Instead of editing this file,
# please use the migrations feature of Active Record to incrementally modify your database, and
# then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your database schema. If you need
# to create the application database on another system, you should be using db:schema:load, not running
# all the migrations from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended to check this file into your version control system.
ActiveRecord::Schema.define(:version => 20100103183928) do
create_table "applicants", :force => true do |t|
t.string "email"
t.text "body"
t.integer "job_id"
t.datetime "created_at"
t.datetime "updated_at"
t.string "cv_file_name"
t.string "cv_content_type"
t.integer "cv_file_size"
t.datetime "cv_updated_at"
t.string "token"
end
create_table "assignments", :force => true do |t|
t.integer "user_id"
t.integer "role_id"
t.datetime "created_at"
t.datetime "updated_at"
end
+ create_table "brain_busters", :force => true do |t|
+ t.string "question"
+ t.string "answer"
+ end
+
create_table "categories", :force => true do |t|
t.string "name"
t.string "permalink"
t.integer "position", :default => 0
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "frameworks", :force => true do |t|
t.string "name"
t.string "permalink"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "jobs", :force => true do |t|
t.integer "type_id", :default => 0
t.integer "price_from"
t.integer "price_to"
t.boolean "remote_job"
t.string "title"
t.string "permalink"
t.text "description"
t.date "end_at"
t.string "company_name"
t.string "website"
t.integer "localization_id"
t.string "nip"
t.string "regon"
t.string "krs"
t.string "email"
t.datetime "created_at"
t.datetime "updated_at"
t.integer "framework_id"
t.float "rank"
t.string "token"
t.boolean "published"
t.integer "visits_count", :default => 0
t.boolean "apply_online", :default => true
t.integer "applicants_count", :default => 0
t.integer "category_id"
end
create_table "localizations", :force => true do |t|
t.string "name"
t.string "permalink"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "pages", :force => true do |t|
t.string "name"
t.string "permalink"
t.text "body"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "roles", :force => true do |t|
t.string "name"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "users", :force => true do |t|
t.string "login"
t.string "email", :null => false
t.string "crypted_password", :null => false
t.string "password_salt", :null => false
t.string "persistence_token", :null => false
t.integer "login_count", :default => 0, :null => false
t.datetime "last_request_at"
t.datetime "last_login_at"
t.datetime "current_login_at"
t.string "last_login_ip"
t.string "current_login_ip"
t.datetime "created_at"
t.datetime "updated_at"
+ t.integer "visits_count", :default => 0
end
add_index "users", ["email"], :name => "index_users_on_email"
add_index "users", ["last_request_at"], :name => "index_users_on_last_request_at"
add_index "users", ["login"], :name => "index_users_on_login"
add_index "users", ["persistence_token"], :name => "index_users_on_persistence_token"
create_table "visits", :force => true do |t|
t.integer "job_id"
t.datetime "created_at"
t.datetime "updated_at"
t.integer "ip", :limit => 8
end
end
diff --git a/doc/informacje.txt b/doc/informacje.txt
new file mode 100644
index 0000000..23bb4d0
--- /dev/null
+++ b/doc/informacje.txt
@@ -0,0 +1,9 @@
+DziÄki serwisowi webpraca.net bÄdziesz mógÅ dodawaÄ i przeglÄ
daÄ oferty pracy oraz zleceÅ z branży IT. Skutecznie rekrutuj z nami pracowników, freelancerów. Serwis posiada unikatowÄ
funkcjÄ oceny oferty dziÄki czemu wcale nie musisz pÅaciÄ aby twoja oferta zostaÅa wyróżniona. Ocenie podlega iloÅÄ wprowadzonych informacji przez zleceniodawcÄ(strona firmy, NIP, REGON, KRS, wideÅki zarobkowe itp. im wiÄcej szczegóÅów tym lepiej) oraz ile osób wyÅwietli ofertÄ i bÄdzie niÄ
zainteresowane(poprzez formularz umożliwiajÄ
cy przesyÅanie aplikacji online w ofercie).
+
+*GÅówne funkcje serwisu*
+* dodawanie ofert(bez zbÄdnej rejestracji. Dostaniesz e-mail z specjalnym linkiem dziÄki któremu bÄdziesz mógÅ edytowaÄ i usuwaÄ swoje oferty)
+* możliwoÅÄ aplikacji online(użytkownicy bÄdÄ
mieli specjalny formularz umożliwiajÄ
cy przesyÅanie aplikacji online w ofercie)
+* różne typy ofert(zlecenie, etat, wolontariat, praktyka)
+* publikacja ofert w serwisach mikroblogowych(blip.pl, flaker.pl, pinger.pl, spinacz.pl)
+* kontakt z zleceniodawcÄ
poprzez specjalny formularz(zabespieczenie antyspamowe)
+* aplikacja online w ofercie(z możliwoÅciÄ
wysÅania CV)
\ No newline at end of file
diff --git a/doc/regulamin.txt b/doc/regulamin.txt
new file mode 100644
index 0000000..56f9fe9
--- /dev/null
+++ b/doc/regulamin.txt
@@ -0,0 +1,29 @@
+Przed dodaniem oferty w serwisie webpraca.net należy przeczytaÄ poniższy regulamin. Dodanie oferty jest jednoczesnym potwierdzeniem zapoznania siÄ z treÅciÄ
poniższego regulaminu i wyrażeniem zgody na wszystkie punkty.
+
+*Serwis zastrzega sobie prawo do usuniÄcia oferty bez ostrzeżenia oraz refundacji kosztów w przypadku:*
+* skÅadania faÅszywej oferty lub usÅugÄ która posÅuży do celu przestÄpczego lub w każdym innym przypadku podejrzenia, że Użytkownik dopuszcza siÄ przestÄpstwa Åciganego z urzÄdu
+* umieszczania obraźliwych wpisów lub komentarzy, treÅci o zawartoÅci pornograficznej, rasistowskiej lub niezgodnej z obowiÄ
zujÄ
cymi w Polsce przepisami prawa, normami spoÅecznymi lub obyczajowymi,
+* naruszenia prawa autorskiego,
+* Åwiadomego lub nieÅwiadomego powodowania niestabilnoÅci systemu i usÅug zwiÄ
zanych z serwisem za pomocÄ
mechanizmów informatycznych, inne dziaÅania Użytkownika, które zostanÄ
uznane za szkodliwe dla serwisu.
+
+*Administrator serwisu webpraca.net nie ponosi odpowiedzialnoÅci za:*
+* oferty umieszczane przez Użytkowników
+* skutki wejÅcia w posiadanie przez osoby trzecie hasÅa Użytkownika
+* przerwy w funkcjonowaniu serwisu zaistniaÅe z przyczyn technicznych np.: konserwacja, przeglÄ
d, wymiana sprzÄtu,
+* utratÄ danych spowodowanÄ
awariÄ
sprzÄtu, systemu lub też innymi okolicznoÅciami niezależnymi od Administratora serwisu.
+* w wypadku opisanym w ustÄpach powyższych Serwis nie ponosi odpowiedzialnoÅci za szkody powstaÅe w wyniku zablokowania lub usuniÄcia ZleceÅ/Ofert.
+
+*Spis usÅug zakazanych*
+* zgÅaszanie zapotrzebowania w Serwisie na usÅugi, które naruszajÄ
obowiÄ
zujÄ
ce prawo lub prawa osób trzecich jest zakazane.
+* serwis nie ponosi odpowiedzialnoÅci za niezgodne z prawdÄ
oÅwiadczenia Użytkowników co do posiadanych przez nich praw, w tym praw autorskich do utworu, koncesji, pozwoleÅ, czy licencji.
+* serwis nie bada, czy Użytkownikowi przysÅugujÄ
wspomniane wyżej koncesje, prawa, licencje itp.
+
+*Administrator serwisu webpraca.net zastrzega sobie prawo do:*
+* ograniczenia funkcjonalnoÅci
+* wprowadzania zmian w obrÄbie niniejszego regulaminu w dowolnym czasie bez wczeÅniejszego informowania o tym,
+* zaprzestania Åwiadczenia usÅug bez powiadomienia Użytkowników serwisu.
+* usuniÄcia dowolnej oferty bez podania przyczyn lub bez wczeÅniejszego powiadomienia o tym autora oferty
+
+*Postanowienia koÅcowe*
+* do spraw które nie sÄ
wprost opisane w niniejszym regulaminie majÄ
zastosowanie przepisy Kodeksu Cywilnego.
+* nieznajomoÅÄ powyższych zasad nie zwalnia z konsekwencji ich Åamania
\ No newline at end of file
diff --git a/public/stylesheets/scaffold.css b/public/stylesheets/scaffold.css
new file mode 100644
index 0000000..093c209
--- /dev/null
+++ b/public/stylesheets/scaffold.css
@@ -0,0 +1,54 @@
+body { background-color: #fff; color: #333; }
+
+body, p, ol, ul, td {
+ font-family: verdana, arial, helvetica, sans-serif;
+ font-size: 13px;
+ line-height: 18px;
+}
+
+pre {
+ background-color: #eee;
+ padding: 10px;
+ font-size: 11px;
+}
+
+a { color: #000; }
+a:visited { color: #666; }
+a:hover { color: #fff; background-color:#000; }
+
+.fieldWithErrors {
+ padding: 2px;
+ background-color: red;
+ display: table;
+}
+
+#errorExplanation {
+ width: 400px;
+ border: 2px solid red;
+ padding: 7px;
+ padding-bottom: 12px;
+ margin-bottom: 20px;
+ background-color: #f0f0f0;
+}
+
+#errorExplanation h2 {
+ text-align: left;
+ font-weight: bold;
+ padding: 5px 5px 5px 15px;
+ font-size: 12px;
+ margin: -7px;
+ background-color: #c00;
+ color: #fff;
+}
+
+#errorExplanation p {
+ color: #333;
+ margin-bottom: 0;
+ padding: 5px;
+}
+
+#errorExplanation ul li {
+ font-size: 12px;
+ list-style: square;
+}
+
diff --git a/test/fixtures/admin_frameworks.yml b/test/fixtures/admin_frameworks.yml
new file mode 100644
index 0000000..157d747
--- /dev/null
+++ b/test/fixtures/admin_frameworks.yml
@@ -0,0 +1,7 @@
+# Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html
+
+one:
+ name: MyString
+
+two:
+ name: MyString
diff --git a/test/functional/admin/frameworks_controller_test.rb b/test/functional/admin/frameworks_controller_test.rb
new file mode 100644
index 0000000..14b1f60
--- /dev/null
+++ b/test/functional/admin/frameworks_controller_test.rb
@@ -0,0 +1,45 @@
+require 'test_helper'
+
+class Admin::FrameworksControllerTest < ActionController::TestCase
+ test "should get index" do
+ get :index
+ assert_response :success
+ assert_not_nil assigns(:admin_frameworks)
+ end
+
+ test "should get new" do
+ get :new
+ assert_response :success
+ end
+
+ test "should create framework" do
+ assert_difference('Admin::Framework.count') do
+ post :create, :framework => { }
+ end
+
+ assert_redirected_to framework_path(assigns(:framework))
+ end
+
+ test "should show framework" do
+ get :show, :id => admin_frameworks(:one).to_param
+ assert_response :success
+ end
+
+ test "should get edit" do
+ get :edit, :id => admin_frameworks(:one).to_param
+ assert_response :success
+ end
+
+ test "should update framework" do
+ put :update, :id => admin_frameworks(:one).to_param, :framework => { }
+ assert_redirected_to framework_path(assigns(:framework))
+ end
+
+ test "should destroy framework" do
+ assert_difference('Admin::Framework.count', -1) do
+ delete :destroy, :id => admin_frameworks(:one).to_param
+ end
+
+ assert_redirected_to admin_frameworks_path
+ end
+end
diff --git a/test/unit/admin/framework_test.rb b/test/unit/admin/framework_test.rb
new file mode 100644
index 0000000..a776e35
--- /dev/null
+++ b/test/unit/admin/framework_test.rb
@@ -0,0 +1,8 @@
+require 'test_helper'
+
+class Admin::FrameworkTest < ActiveSupport::TestCase
+ # Replace this with your real tests.
+ test "the truth" do
+ assert true
+ end
+end
diff --git a/test/unit/helpers/admin/frameworks_helper_test.rb b/test/unit/helpers/admin/frameworks_helper_test.rb
new file mode 100644
index 0000000..a106e5e
--- /dev/null
+++ b/test/unit/helpers/admin/frameworks_helper_test.rb
@@ -0,0 +1,4 @@
+require 'test_helper'
+
+class Admin::FrameworksHelperTest < ActionView::TestCase
+end
|
macbury/webpraca
|
e6c0206d5957c14f78f20bcee11c97bf0960e068
|
404 i 500 bledy
|
diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb
index 122e77c..e39d520 100644
--- a/app/controllers/application_controller.rb
+++ b/app/controllers/application_controller.rb
@@ -1,93 +1,118 @@
class ApplicationController < ActionController::Base
include ExceptionNotifiable
helper :all # include all helpers, all the time
protect_from_forgery # See ActionController::RequestForgeryProtection for details
filter_parameter_logging :password, :password_confirmation
helper_method :current_user_session, :current_user, :logged_in?, :own?
before_filter :staging_authentication, :seo, :user_for_authorization
+
+ def rescue_action_in_public(exception)
+ case exception
+ when ActiveRecord::RecordNotFound
+ render_404
+ when ActionController::RoutingError
+ render_404
+ when ActionController::UnknownController
+ render_404
+ when ActionController::UnknownAction
+ render_404
+ else
+ render_500
+ end
+ end
protected
+ def render_404
+ @page_title = ["BÅÄ
d 404", "Nie znaleziono strony"]
+ render :template => "shared/error_404", :layout => 'application', :status => :not_found
+ end
+
+ def render_500
+ @page_title = ["BÅÄ
d 500", "CoÅ poszÅo nie tak"]
+ render :template => "shared/error_500", :layout => 'application', :status => :internal_server_error
+ end
+
def not_for_production
redirect_to root_path if Rails.env == "production"
end
# Ads Position
# :bottom, :right, :none
def self.ads_pos(position, options = {})
before_filter(options) do |controller|
controller.instance_variable_set('@ads_pos', position)
end
end
def user_for_authorization
Authorization.current_user = self.current_user
end
def permission_denied
flash[:error] = "Nie masz wystarczajÄ
cych uprawnieÅ aby móc odwiedziÄ tÄ
stronÄ"
redirect_to root_url
end
def seo
@ads_pos = :bottom
@standard_tags = WebSiteConfig['website']['tags']
set_meta_tags :description => WebSiteConfig['website']['description'],
:keywords => @standard_tags
end
def staging_authentication
if ENV['RAILS_ENV'] == 'staging'
authenticate_or_request_with_http_basic do |user_name, password|
user_name == "change this" && password == "and this"
end
end
end
def current_user_session
@current_user_session ||= UserSession.find
return @current_user_session
end
def current_user
@current_user ||= self.current_user_session && self.current_user_session.user
return @current_user
end
def logged_in?
!self.current_user.nil?
end
def own?(object)
logged_in? && self.current_user.own?(object)
end
def store_location
session[:return_to] = request.request_uri
end
def redirect_back_or_default
redirect_to session[:return_to] || admin_path
session[:return_to] = nil
end
def login_required
unless logged_in?
respond_to do |format|
format.html do
flash[:error] = "Musisz siÄ zalogowaÄ aby móc objrzeÄ tÄ
strone"
store_location
redirect_to login_path
end
format.js { render :js => "window.location = #{login_path.inspect};" }
end
else
@page_title = ["Panel administracyjny"]
end
end
end
\ No newline at end of file
diff --git a/app/stylesheets/ui.less b/app/stylesheets/ui.less
index 484f295..f0e224b 100644
--- a/app/stylesheets/ui.less
+++ b/app/stylesheets/ui.less
@@ -1,597 +1,597 @@
/* Defaults */
@text_color: #393733;
@link_color: #31627E;
@hover_color: #FF5917;
/* Global */
body {
margin: 0;
padding: 0;
font: 12px Arial;
color: @text_color;
overflow: auto;
background: #76787B url('/images/bkg.png') repeat-x top;
}
h1, h2, h3, h4 { margin: 0 0 5px 0; }
a { color: @link_color; cursor: pointer; outline: none !important; text-decoration: none; }
a:hover, a:focus { color: @hover_color; }
a img { border: 0; }
/* Table */
table { border-collapse: collapse; width: 100%; }
td, th {
font-size:11px;
border-bottom:1px solid #eee;
padding:5px;
}
th { text-align:left; font-size:12px; }
thead th { font-weight:bold; color:#666; padding:2px 5px; font-size:11px; background:#e1e1e1 url(/images/nav-bg.gif) top left repeat-x; border-left:1px solid #ddd; border-bottom:1px solid #ddd; }
thead th:first-child { border-left:none !important; }
thead th.optional { font-weight:normal !important; }
tr.alt { background:#f6f6f6; }
/* IDS */
.prices input[type="text"] { width: 50px !important; text-align: right; }
#job_captcha_image, #applicant_captcha_image, .captcha img { margin-bottom: -22px !important; margin-right: 10px !important; }
#job_captcha_solution, #applicant_captcha_solution, .captcha input { width: 200px !important; }
#AdTaily_Widget_Container { padding-top: 5px; }
/* Custom class */
.rounded_corners (@radius: 5px) {
-moz-border-radius: @radius;
-webkit-border-radius: @radius;
border-radius: @radius;
-o-border-radius: @radius;
}
.rounded_corner_top_left(@radius: 5px) { -moz-border-radius-topleft: @radius; -webkit-border-top-left-radius: @radius; border-top-left-radius: @radius; }
.rounded_corner_top_right(@radius: 5px) { -moz-border-radius-topright: @radius; -webkit-border-top-right-radius: @radius; border-top-right-radius: @radius; }
.rounded_corner_bottom_left(@radius: 5px) { -moz-border-radius-bottomleft: @radius; -webkit-border-bottom-left-radius: @radius; border-bottom-left-radius: @radius; }
.rounded_corner_bottom_right(@radius: 5px) { -moz-border-radius-bottomright: @radius; -webkit-border-bottom-right-radius: @radius; border-bottom-right-radius: @radius; }
.reset { margin: 0; padding: 0; list-style: none; }
.text_center { text-align: center; }
.text_right { text-align: right; }
.clear { clear: both; }
.info { text-align: center; color: #ddd; font-size: 28px; font-weight: bold; }
.loader { background: transparent url('/images/ajax.gif') no-repeat center center; height: 20px; display: none; }
.right { float: right; }
.left { float: left; }
/* Flash */
.flash {
background-color: #A4E1A2;
border: 1px solid #DDE3D7;
text-shadow: #C0FDE3 0px 1px 0px;
.rounded_corners(5px);
color: #094808;
margin-top: 10px;
opacity: 0.8;
padding: 10px;
}
.flash.error {
background-color: #AF2B2B;
color: #fff;
border: 1px solid #DA3536;
text-shadow: #000 0px 1px 0px;
}
.flash:hover { opacity: 1.0; }
.flash .dismiss {
background: transparent url('/images/close.png') no-repeat !important;
float: right;
height: 10px;
width: 9px;
text-indent: 9999px;
overflow: hidden;
}
.flash p {
font-weight: normal;
line-height: 15px;
margin: 0px;
}
.flash_error {
background: #AF2B2B url('../images/icon-error.png') 20px center no-repeat;
color: #fff;
border: 1px solid #DA3536;
text-shadow: #000 0px 1px 0px;
}
/* Buttons */
.buttons { margin: 0 5px; }
.button {
background: #DDD url('../images/button.png') repeat-x 0px 0px;
border: 1px solid #999;
display: inline-block;
outline: none;
-webkit-box-shadow: rgba(0, 0, 0, 0.117188) 0px 1px 0px;
}
.button > input[type="button"], .button > input[type="submit"], .button > a {
border: none;
line-height: 23px;
height: 23px;
padding: 0 10px;
color: #333 !important;
font-weight: bold;
text-decoration: none;
font-size: 11px;
cursor: default;
background: transparent;
}
.button:active {
background-color: #ddd;
background-image: none;
}
.button img {
margin-bottom: -4px;
margin-right: 5px;
width: 16px;
height: 16px;
}
.button.right { float: right; }
/* TextFields */
select { min-width: 150px; }
input[type="text"], input[type="password"], textarea {
padding: 4px 3px !important;
border: 1px solid #96A6C5;
color: #000;
}
textarea { height: 200px; min-height: 200px; }
input[type="text"]:focus, input[type="password"]:focus, textarea:focus {
background-color: #e6f7ff;
border-bottom: 1px solid #7FAEFF;
border-right: 1px solid #7FAEFF;
border-left: 1px solid #4478A8;
border-top: 1px solid #4478A8;
}
form > fieldset {
border: 2px solid #ddd !important;
.rounded_corners;
padding: 10px 15px !important;
margin: 10px 5px !important;
}
form > fieldset > legend {
font-weight: bold;
padding: 0 15px 0px 0 !important;
margin-left: -22px !important;
background: #fff;
font-size: 16px;
color: #333 !important;
}
/* Wrapper */
@wrapper_width: 900px;
.wrapper {
margin: 0px auto;
width: @wrapper_width;
min-height: 500px;
}
/* Header */
@header_height: 80px;
.wrapper > .header {
height: @header_height;
width: @wrapper_width;
position:relative;
}
@logo_width: 347px;
@menu_color: #35373A;
@header_link_color: #D8D8D9;
.header > h1#logo {
left: 8px;
position: absolute;
top: 10px;
width: @logo_width;
}
.header > h1#logo a { color: #fff; font: 28px "Trebuchet MS"; font-weight: bold; }
.header > h1#logo a:hover { background: transparent; }
.header > ul.categories {
.reset;
position: absolute;
bottom: 5px;
left: 0px;
}
.header > ul.categories li {
display:inline;
margin-left: 3px;
}
.header > ul.categories li > a {
padding: 5px 10px;
margin-top: 5px;
font-size: 13px;
color: @header_link_color;
.rounded_corner_top_left;
.rounded_corner_top_right;
background: @menu_color;
}
.header > ul.categories li > a:hover { background: #5d5f62; }
.header > ul.categories li > .selected { color: #fff; background: #2A2B2D !important; }
.header > ul.menu {
.reset;
.rounded_corner_bottom_left;
.rounded_corner_bottom_right;
position:absolute;
top: 0px;
padding: 5px 10px;
right: 0px;
background: @menu_color;
}
.header > ul.menu li{
display:inline;
margin-left: 3px;
padding-left: 6px;
- border-left: 1px dotted #393B3E;
+ border-left: 1px dotted #212326;
background-color:transparent;
font-size: 10px;
font-weight: bold;
color: @header_link_color;
}
.header > ul.menu li a { color: @header_link_color; }
.header > ul.menu li a:hover { color: #fff; background: transparent; }
.header > ul.menu li:first-child { border: 0; margin-left: 0; padding-left: 0; }
/* Sidebar */
@sidebar_width: 200px;
.wrapper > .sidebar {
float: right;
width: @sidebar_width;
margin-top: 20px;
}
.wrapper > .sidebar ul { .reset; }
/* content */
@content_padding_right: 10px;
@content_width: @wrapper_width - @sidebar_width - @content_padding_right;
.wrapper > .content {
float: left;
width: @content_width;
padding-right: @content_padding_right;
margin-top: 20px;
}
/*.wrapper > .content p { margin: 0 0 10px 0; padding: 0;} */
/* Box */
.box {
margin-bottom: 10px;
padding: 6px;
background: #9C9C9C;
.rounded_corners(5px);
}
@box_div_border_radius: 4px;
.box > div {
background: #fff;
margin-bottom: 10px;
padding-bottom: 5px;
.rounded_corners(@box_div_border_radius);
}
.box > div:last-child { margin-bottom: 0; }
@title_height: 39px;
@sidebar_title_height: 29px;
.box .title {
height: @title_height;
.rounded_corner_top_right(@box_div_border_radius);
.rounded_corner_top_left(@box_div_border_radius);
display: block;
background: #fff url('/images/title-header.png') repeat-x bottom;
border-bottom: 1px solid #F1EFBD;
}
.box .title > h2, .box .title > h3 {
margin: 0;
padding: 1px 10px 0 10px;
line-height: @title_height - 1px;
font-weight: normal;
font-size: 18px;
color: #656666;
}
.box .title > h3 {
font-size: 16px;
line-height: @sidebar_title_height - 1px;
}
.box .title > h2 > span, .box .title > h3 > span { color: #8E8F8F; }
.box > div form { margin: 5px !important; }
.box p {
margin: 10px;
}
.sidebar .box .title, .box .title.mini {
height: @sidebar_title_height;
}
/* list */
.list {
.reset;
.clear;
}
.list > li { clear: both; padding: 5px; }
.list > .alt { background:#f6f6f6; }
.list > li > .ranked { font-weight: bold; }
.list > li .handle { cursor: move; margin: 3px 5px 0 5px; }
.list > li > .badge {
float: right;
min-width: 18px;
padding: 2px 3px;
font-weight: bold;
font-size: 10px;
color: #fff;
background: #8798BB;
.rounded_corners(7px);
text-align: center;
}
.list > li > .rank {
.rounded_corners(2px);
text-align: center;
min-width: 18px;
padding: 2px 3px;
font-weight: bold;
font-size: 9px;
float: right;
background: #FFFF98;
border: 1px solid #E2E28C;
margin-top: -1px;
}
.list > li > .date {
font-size: 11px;
font-style: italic;
color: #7C7C7C;
}
/* more button */
.more {
background: #fff url('/images/more.gif') 0% 0% repeat-x;
border: 1px solid #DDD;
border-bottom: 1px solid #AAA;
border-right: 1px solid #AAA;
display: block;
font-size: 14px;
font-weight: bold;
color: inherit;
height: 22px;
line-height: 1.5em;
padding: 6px 0px;
text-align: center;
text-shadow: #fff 1px 1px 1px;
.rounded_corners(6px);
}
.more:hover {
background-position: 0% -78px;
border: 1px solid #BBB;
color: inherit;
}
.more:active {
background-position: 0% -38px;
color: #666;
}
/* Etykiety */
.etykieta {
display: block;
float: left;
font-size: 9px;
margin-right: 5px;
margin-top: -1px;
text-align: center;
width: 60px;
.rounded_corners(2px);
padding: 2px 3px;
color: #fff;
}
.etykieta:hover { color: #fff; }
.etykieta.zdalnie {
background: #357CCB;
border: 1px solid #2C6AB0;
}
.etykieta.zlecenie {
background: #F8854E;
border: 1px solid #D27244;
}
.etykieta.etat {
background: #408000;
border: 1px solid #366E01;
}
.etykieta.praktyka {
background: #FF6;
border: 1px solid #E2E25C;
color: #31627E;
}
.praktyka:hover { color: #31627E; }
.etykieta.wolontariat {
background: #D6D6D6;
border: 1px solid #B1B1B1;
color: #31627E;
}
.wolontariat:hover { color: #31627E; }
/* Pagination */
.pagination { background: white; margin: 5px 5px 0 5px; }
.pagination a, .pagination span {
padding: .2em .5em;
display: block;
float: left;
margin-right: 1px;
}
.pagination span.disabled {
color: #999;
border: 1px solid #DDD;
}
.pagination span.current {
font-weight: bold;
background: #2E6AB1;
color: white;
border: 1px solid #2E6AB1;
}
.pagination a {
text-decoration: none;
color: #105CB6;
border: 1px solid #9AAFE5;
}
.pagination a:hover, .pagination a:focus {
color: #003;
border-color: #003;
background-color: transparent;
}
.pagination .page_info {
background: #2E6AB1;
color: white;
padding: .4em .6em;
width: 22em;
margin-bottom: .3em;
text-align: center;
}
.pagination .page_info b {
color: #003;
background: #6aa6ed;
padding: .1em .25em;
}
.pagination:after {
content: ".";
display: block;
height: 0;
clear: both;
visibility: hidden;
}
* html .pagination { height: 1%; }
*:first-child+html .pagination { overflow: hidden; }
/* describe list */
@dt_width: 180px;
@dt_padding_right: 10px;
@dl_padding_left: 10px;
dl {
padding: 0px;
margin: 10px 0 0 0;
display: block;
}
dl dt {
width: @dt_width;
text-align: right;
color: #888;
float: left;
display: block;
padding: 0 @dt_padding_right 6px 0;
margin: 0;
}
dl dd {
width: @content_width - @dt_width - @dt_padding_right - @dl_padding_left - 15px;
border-left: 1px solid #ccc;
float: left;
padding: 0 0 10px @dl_padding_left;
margin: 0;
}
dl dd:last-child { padding-bottom: 0px; }
dl dd ul {
padding: 5px 0 0 20px;
margin: 0;
}
/* feed icon */
.feed {
float: right;
margin-top: 5px;
margin-right: -3px;
}
/* footer */
.footer {
margin: 10px auto;
width: @wrapper_width;
color: #D8D8D9;
}
.footer strong a { color: #fff; }
.footer a { color: #D8D8D9; }
.footer a:hover { color: #fff; }
.footer .right { margin-top: 3px; }
\ No newline at end of file
diff --git a/app/views/shared/_footer.html.erb b/app/views/shared/_footer.html.erb
index 3e5fc85..82a3ce0 100644
--- a/app/views/shared/_footer.html.erb
+++ b/app/views/shared/_footer.html.erb
@@ -1,11 +1,11 @@
<div class="footer">
<span class="right">
<%= link_to "Strona gÅówna", root_path %> |
<%= link_to "Oferty", jobs_path %> |
<%= link_to "Szukaj", search_jobs_path %> |
<%= link_to "O nas", "/strona/o-nas/" %> |
<%= link_to "Kontakt", contact_path %> |
<%= link_to "GitHub", "http://github.com/macbury/webpraca" %>
</span>
- <strong><%= link_to "webpraca.net", root_path %></strong> <sup>BETA</sup> © <%= Date.current.year %>.
+ <strong><%= link_to WebSiteConfig['website']['name'], root_path %></strong> <sup>BETA</sup> © <%= Date.current.year %>.
</div>
\ No newline at end of file
diff --git a/app/views/shared/error_404.html.erb b/app/views/shared/error_404.html.erb
new file mode 100644
index 0000000..ae28798
--- /dev/null
+++ b/app/views/shared/error_404.html.erb
@@ -0,0 +1,10 @@
+<div class="box">
+ <div>
+ <div class="title">
+ <h2>Nie znaleziono strony!</h2>
+ </div>
+ <div class="text_center">
+ <img src="/images/404.jpeg" width="440" height="358" alt="404" />
+ </div>
+ </div>
+</div>
diff --git a/app/views/shared/error_500.html.erb b/app/views/shared/error_500.html.erb
new file mode 100644
index 0000000..5c3d55e
--- /dev/null
+++ b/app/views/shared/error_500.html.erb
@@ -0,0 +1,11 @@
+<div class="box">
+ <div>
+ <div class="title">
+ <h2>CoÅ poszÅo nie tak... Aplikacja trafiÅa na nieobsÅugiwany wyjÄ
tek.</h2>
+ </div>
+ <div class="text_center">
+ <img src="/images/500.jpeg" width="500" height="416" alt="500" />
+ </div>
+ </div>
+</div>
+
diff --git a/config/initializers/mailer.rb b/config/initializers/mailer.rb
index d2bdfbc..652fdd1 100644
--- a/config/initializers/mailer.rb
+++ b/config/initializers/mailer.rb
@@ -1,6 +1,5 @@
require "smtp_tls"
-ActionMailer::Base.delivery_method = :smtp
-ActionMailer::Base.raise_delivery_errors = true
+ActionMailer::Base.delivery_method = :smtp
ActionMailer::Base.default_charset = 'utf-8'
ActionMailer::Base.perform_deliveries = true
ActionMailer::Base.smtp_settings = YAML.load_file("#{RAILS_ROOT}/config/mailer.yml")[Rails.env]
\ No newline at end of file
diff --git a/public/images/404.jpeg b/public/images/404.jpeg
new file mode 100644
index 0000000..2516985
Binary files /dev/null and b/public/images/404.jpeg differ
diff --git a/public/images/404.png b/public/images/404.png
new file mode 100644
index 0000000..2617ee0
Binary files /dev/null and b/public/images/404.png differ
diff --git a/public/images/500.jpeg b/public/images/500.jpeg
new file mode 100644
index 0000000..429c4fe
Binary files /dev/null and b/public/images/500.jpeg differ
diff --git a/vendor/plugins/stupid_simple_config b/vendor/plugins/stupid_simple_config
new file mode 160000
index 0000000..a429f6c
--- /dev/null
+++ b/vendor/plugins/stupid_simple_config
@@ -0,0 +1 @@
+Subproject commit a429f6cea09c438f0cd28ffe126d6400352936a3
|
dido/arcueid
|
f355a621f8250152b3b60d5aecf464e5e84936ec
|
add a check for the stack pointer value after menv call
|
diff --git a/java/test/org/arcueidarc/nekoarc/vm/VirtualMachineTest.java b/java/test/org/arcueidarc/nekoarc/vm/VirtualMachineTest.java
index 1c80df6..50bc8ca 100644
--- a/java/test/org/arcueidarc/nekoarc/vm/VirtualMachineTest.java
+++ b/java/test/org/arcueidarc/nekoarc/vm/VirtualMachineTest.java
@@ -1,160 +1,169 @@
package org.arcueidarc.nekoarc.vm;
import static org.junit.Assert.*;
import org.arcueidarc.nekoarc.NekoArcException;
import org.arcueidarc.nekoarc.Nil;
import org.arcueidarc.nekoarc.Unbound;
import org.arcueidarc.nekoarc.types.Fixnum;
import org.arcueidarc.nekoarc.vm.VirtualMachine;
import org.junit.Test;
public class VirtualMachineTest
{
@Test
public void testInstArg()
{
byte data[] = { 0x01, 0x00, 0x00, 0x00 };
VirtualMachine vm = new VirtualMachine(1024);
vm.load(data, 0);
assertEquals(1, vm.instArg());
byte data2[] = { (byte) 0xff, 0x00, 0x00, 0x00 };
vm.load(data2, 0);
assertEquals(255, vm.instArg());
byte data3[] = { (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff };
vm.load(data3, 0);
assertEquals(-1, vm.instArg());
byte data4[] = { (byte) 0x5d, (byte) 0xc3, (byte) 0x1f, (byte) 0x21 };
vm.load(data4, 0);
assertEquals(555729757, vm.instArg());
// two's complement negative
byte data5[] = { (byte) 0xa3, (byte) 0x3c, (byte) 0xe0, (byte) 0xde };
vm.load(data5, 0);
assertEquals(-555729757, vm.instArg());
}
@Test
public void testSmallInstArg()
{
byte data[] = { (byte) 0x12, (byte) 0xff };
VirtualMachine vm = new VirtualMachine(1024);
vm.load(data, 0);
assertEquals(0x12, vm.smallInstArg());
assertEquals(-1, vm.smallInstArg());
}
@Test
public void testEnv() throws NekoArcException
{
VirtualMachine vm = new VirtualMachine(1024);
try {
vm.getenv(0, 0);
fail("exception not thrown");
} catch (NekoArcException e) {
assertEquals("environment depth exceeded", e.getMessage());
}
try {
vm.setenv(0, 0, Nil.NIL);
fail("exception not thrown");
} catch (NekoArcException e) {
assertEquals("environment depth exceeded", e.getMessage());
}
vm.push(Fixnum.get(1));
vm.push(Fixnum.get(2));
vm.push(Fixnum.get(3));
vm.mkenv(3, 2);
vm.push(Fixnum.get(4));
vm.push(Fixnum.get(5));
vm.mkenv(2, 4);
vm.setenv(1, 3, Fixnum.get(6));
vm.setenv(0, 2, Fixnum.get(7));
assertEquals(1, ((Fixnum)vm.getenv(1, 0)).fixnum);
assertEquals(2, ((Fixnum)vm.getenv(1, 1)).fixnum);
assertEquals(3, ((Fixnum)vm.getenv(1, 2)).fixnum);
assertEquals(6, ((Fixnum)vm.getenv(1, 3)).fixnum);
assertTrue(vm.getenv(1, 4).is(Unbound.UNBOUND));
assertEquals(4, ((Fixnum)vm.getenv(0, 0)).fixnum);
assertEquals(5, ((Fixnum)vm.getenv(0, 1)).fixnum);
assertEquals(7, ((Fixnum)vm.getenv(0, 2)).fixnum);
assertTrue(vm.getenv(0, 3).is(Unbound.UNBOUND));
assertTrue(vm.getenv(0, 4).is(Unbound.UNBOUND));
assertTrue(vm.getenv(0, 5).is(Unbound.UNBOUND));
}
@Test
public void testmenv() throws NekoArcException
{
VirtualMachine vm = new VirtualMachine(1024);
// New environment just as big as the old environment
vm.push(Fixnum.get(0));
vm.push(Fixnum.get(1));
vm.push(Fixnum.get(2));
+ assertEquals(3, vm.getSP());
+
vm.mkenv(3, 0);
+ assertEquals(6, vm.getSP());
assertEquals(0, ((Fixnum)vm.getenv(0, 0)).fixnum);
assertEquals(1, ((Fixnum)vm.getenv(0, 1)).fixnum);
assertEquals(2, ((Fixnum)vm.getenv(0, 2)).fixnum);
vm.push(Fixnum.get(3));
vm.push(Fixnum.get(4));
vm.push(Fixnum.get(5));
vm.menv(3);
vm.mkenv(3, 0);
+ assertEquals(6, vm.getSP());
assertEquals(3, ((Fixnum)vm.getenv(0, 0)).fixnum);
assertEquals(4, ((Fixnum)vm.getenv(0, 1)).fixnum);
assertEquals(5, ((Fixnum)vm.getenv(0, 2)).fixnum);
// Reset environment and stack pointer
vm.setenvreg(Nil.NIL);
vm.setSP(0);
// New environment smaller than old environment
vm.push(Fixnum.get(0));
vm.push(Fixnum.get(1));
vm.push(Fixnum.get(2));
vm.mkenv(3, 0);
assertEquals(0, ((Fixnum)vm.getenv(0, 0)).fixnum);
assertEquals(1, ((Fixnum)vm.getenv(0, 1)).fixnum);
assertEquals(2, ((Fixnum)vm.getenv(0, 2)).fixnum);
vm.push(Fixnum.get(6));
vm.push(Fixnum.get(7));
vm.menv(2);
vm.mkenv(2, 0);
+ assertEquals(5, vm.getSP());
assertEquals(6, ((Fixnum)vm.getenv(0, 0)).fixnum);
assertEquals(7, ((Fixnum)vm.getenv(0, 1)).fixnum);
+ // Reset environment and stack pointer
+ vm.setenvreg(Nil.NIL);
+ vm.setSP(0);
+
// New environment larger than old environment
- // New environment smaller than old environment
vm.push(Fixnum.get(0));
vm.push(Fixnum.get(1));
vm.push(Fixnum.get(2));
vm.mkenv(3, 0);
assertEquals(0, ((Fixnum)vm.getenv(0, 0)).fixnum);
assertEquals(1, ((Fixnum)vm.getenv(0, 1)).fixnum);
assertEquals(2, ((Fixnum)vm.getenv(0, 2)).fixnum);
vm.push(Fixnum.get(8));
vm.push(Fixnum.get(9));
vm.push(Fixnum.get(10));
vm.push(Fixnum.get(11));
vm.menv(4);
vm.mkenv(4, 0);
+ assertEquals(7, vm.getSP());
assertEquals(8, ((Fixnum)vm.getenv(0, 0)).fixnum);
assertEquals(9, ((Fixnum)vm.getenv(0, 1)).fixnum);
assertEquals(10, ((Fixnum)vm.getenv(0, 2)).fixnum);
assertEquals(11, ((Fixnum)vm.getenv(0, 3)).fixnum);
}
}
|
dido/arcueid
|
c17c005048b2a0e48db03c0663ae9d581eb7f5cd
|
remove warnings
|
diff --git a/java/src/org/arcueidarc/nekoarc/util/ObjectMap.java b/java/src/org/arcueidarc/nekoarc/util/ObjectMap.java
index a7c5e07..310affe 100644
--- a/java/src/org/arcueidarc/nekoarc/util/ObjectMap.java
+++ b/java/src/org/arcueidarc/nekoarc/util/ObjectMap.java
@@ -1,546 +1,548 @@
package org.arcueidarc.nekoarc.util;
import java.util.Random;
/** An unordered map. This implementation is a cuckoo hash map using 3 hashes, random walking, and a small stash for problematic
* keys. Null keys are not allowed. Null values are allowed. No allocation is done except when growing the table size. <br>
* <br>
* This map performs very fast get, containsKey, and remove (typically O(1), worst case O(log(n))). Put may be a bit slower,
* depending on hash collisions. Load factors greater than 0.91 greatly increase the chances the map will have to rehash to the
* next higher POT size.
* @author Nathan Sweet */
public class ObjectMap<K, V>
{
- private static final int PRIME1 = 0xbe1f14b1;
+// private static final int PRIME1 = 0xbe1f14b1;
private static final int PRIME2 = 0xb4b82e39;
private static final int PRIME3 = 0xced1c241;
public int size;
K[] keyTable;
V[] valueTable;
int capacity, stashSize;
private float loadFactor;
private int hashShift, mask, threshold;
private int stashCapacity;
private int pushIterations;
public static Random random = new Random();
/** Returns a random number between 0 (inclusive) and the specified value (inclusive). */
public static final int random (int range) {
return random.nextInt(range + 1);
}
/** Creates a new map with an initial capacity of 32 and a load factor of 0.8. This map will hold 25 items before growing the
* backing table. */
public ObjectMap () {
this(32, 0.8f);
}
/** Creates a new map with a load factor of 0.8. This map will hold initialCapacity * 0.8 items before growing the backing
* table. */
public ObjectMap (int initialCapacity) {
this(initialCapacity, 0.8f);
}
public static int nextPowerOfTwo (int value) {
if (value == 0) return 1;
value--;
value |= value >> 1;
value |= value >> 2;
value |= value >> 4;
value |= value >> 8;
value |= value >> 16;
return value + 1;
}
/** Creates a new map with the specified initial capacity and load factor. This map will hold initialCapacity * loadFactor items
* before growing the backing table. */
+ @SuppressWarnings("unchecked")
public ObjectMap (int initialCapacity, float loadFactor) {
if (initialCapacity < 0) throw new IllegalArgumentException("initialCapacity must be >= 0: " + initialCapacity);
if (initialCapacity > 1 << 30) throw new IllegalArgumentException("initialCapacity is too large: " + initialCapacity);
capacity = nextPowerOfTwo(initialCapacity);
if (loadFactor <= 0) throw new IllegalArgumentException("loadFactor must be > 0: " + loadFactor);
this.loadFactor = loadFactor;
threshold = (int)(capacity * loadFactor);
mask = capacity - 1;
hashShift = 31 - Integer.numberOfTrailingZeros(capacity);
stashCapacity = Math.max(3, (int)Math.ceil(Math.log(capacity)) * 2);
pushIterations = Math.max(Math.min(capacity, 8), (int)Math.sqrt(capacity) / 8);
keyTable = (K[])new Object[capacity + stashCapacity];
valueTable = (V[])new Object[keyTable.length];
}
/** Creates a new map identical to the specified map. */
public ObjectMap (ObjectMap<? extends K, ? extends V> map) {
this(map.capacity, map.loadFactor);
stashSize = map.stashSize;
System.arraycopy(map.keyTable, 0, keyTable, 0, map.keyTable.length);
System.arraycopy(map.valueTable, 0, valueTable, 0, map.valueTable.length);
size = map.size;
}
/** Returns the old value associated with the specified key, or null. */
public V put (K key, V value) {
if (key == null) throw new IllegalArgumentException("key cannot be null.");
return put_internal(key, value);
}
private V put_internal (K key, V value) {
K[] keyTable = this.keyTable;
// Check for existing keys.
int hashCode = key.hashCode();
int index1 = hashCode & mask;
K key1 = keyTable[index1];
if (key.equals(key1)) {
V oldValue = valueTable[index1];
valueTable[index1] = value;
return oldValue;
}
int index2 = hash2(hashCode);
K key2 = keyTable[index2];
if (key.equals(key2)) {
V oldValue = valueTable[index2];
valueTable[index2] = value;
return oldValue;
}
int index3 = hash3(hashCode);
K key3 = keyTable[index3];
if (key.equals(key3)) {
V oldValue = valueTable[index3];
valueTable[index3] = value;
return oldValue;
}
// Update key in the stash.
for (int i = capacity, n = i + stashSize; i < n; i++) {
if (key.equals(keyTable[i])) {
V oldValue = valueTable[i];
valueTable[i] = value;
return oldValue;
}
}
// Check for empty buckets.
if (key1 == null) {
keyTable[index1] = key;
valueTable[index1] = value;
if (size++ >= threshold) resize(capacity << 1);
return null;
}
if (key2 == null) {
keyTable[index2] = key;
valueTable[index2] = value;
if (size++ >= threshold) resize(capacity << 1);
return null;
}
if (key3 == null) {
keyTable[index3] = key;
valueTable[index3] = value;
if (size++ >= threshold) resize(capacity << 1);
return null;
}
push(key, value, index1, key1, index2, key2, index3, key3);
return null;
}
/** Skips checks for existing keys. */
private void putResize (K key, V value) {
// Check for empty buckets.
int hashCode = key.hashCode();
int index1 = hashCode & mask;
K key1 = keyTable[index1];
if (key1 == null) {
keyTable[index1] = key;
valueTable[index1] = value;
if (size++ >= threshold) resize(capacity << 1);
return;
}
int index2 = hash2(hashCode);
K key2 = keyTable[index2];
if (key2 == null) {
keyTable[index2] = key;
valueTable[index2] = value;
if (size++ >= threshold) resize(capacity << 1);
return;
}
int index3 = hash3(hashCode);
K key3 = keyTable[index3];
if (key3 == null) {
keyTable[index3] = key;
valueTable[index3] = value;
if (size++ >= threshold) resize(capacity << 1);
return;
}
push(key, value, index1, key1, index2, key2, index3, key3);
}
private void push (K insertKey, V insertValue, int index1, K key1, int index2, K key2, int index3, K key3) {
K[] keyTable = this.keyTable;
V[] valueTable = this.valueTable;
int mask = this.mask;
// Push keys until an empty bucket is found.
K evictedKey;
V evictedValue;
int i = 0, pushIterations = this.pushIterations;
do {
// Replace the key and value for one of the hashes.
switch (random(2)) {
case 0:
evictedKey = key1;
evictedValue = valueTable[index1];
keyTable[index1] = insertKey;
valueTable[index1] = insertValue;
break;
case 1:
evictedKey = key2;
evictedValue = valueTable[index2];
keyTable[index2] = insertKey;
valueTable[index2] = insertValue;
break;
default:
evictedKey = key3;
evictedValue = valueTable[index3];
keyTable[index3] = insertKey;
valueTable[index3] = insertValue;
break;
}
// If the evicted key hashes to an empty bucket, put it there and stop.
int hashCode = evictedKey.hashCode();
index1 = hashCode & mask;
key1 = keyTable[index1];
if (key1 == null) {
keyTable[index1] = evictedKey;
valueTable[index1] = evictedValue;
if (size++ >= threshold) resize(capacity << 1);
return;
}
index2 = hash2(hashCode);
key2 = keyTable[index2];
if (key2 == null) {
keyTable[index2] = evictedKey;
valueTable[index2] = evictedValue;
if (size++ >= threshold) resize(capacity << 1);
return;
}
index3 = hash3(hashCode);
key3 = keyTable[index3];
if (key3 == null) {
keyTable[index3] = evictedKey;
valueTable[index3] = evictedValue;
if (size++ >= threshold) resize(capacity << 1);
return;
}
if (++i == pushIterations) break;
insertKey = evictedKey;
insertValue = evictedValue;
} while (true);
putStash(evictedKey, evictedValue);
}
private void putStash (K key, V value) {
if (stashSize == stashCapacity) {
// Too many pushes occurred and the stash is full, increase the table size.
resize(capacity << 1);
put_internal(key, value);
return;
}
// Store key in the stash.
int index = capacity + stashSize;
keyTable[index] = key;
valueTable[index] = value;
stashSize++;
size++;
}
public V get (K key) {
int hashCode = key.hashCode();
int index = hashCode & mask;
if (!key.equals(keyTable[index])) {
index = hash2(hashCode);
if (!key.equals(keyTable[index])) {
index = hash3(hashCode);
if (!key.equals(keyTable[index])) return getStash(key);
}
}
return valueTable[index];
}
private V getStash (K key) {
K[] keyTable = this.keyTable;
for (int i = capacity, n = i + stashSize; i < n; i++)
if (key.equals(keyTable[i])) return valueTable[i];
return null;
}
/** Returns the value for the specified key, or the default value if the key is not in the map. */
public V get (K key, V defaultValue) {
int hashCode = key.hashCode();
int index = hashCode & mask;
if (!key.equals(keyTable[index])) {
index = hash2(hashCode);
if (!key.equals(keyTable[index])) {
index = hash3(hashCode);
if (!key.equals(keyTable[index])) return getStash(key, defaultValue);
}
}
return valueTable[index];
}
private V getStash (K key, V defaultValue) {
K[] keyTable = this.keyTable;
for (int i = capacity, n = i + stashSize; i < n; i++)
if (key.equals(keyTable[i])) return valueTable[i];
return defaultValue;
}
public V remove (K key) {
int hashCode = key.hashCode();
int index = hashCode & mask;
if (key.equals(keyTable[index])) {
keyTable[index] = null;
V oldValue = valueTable[index];
valueTable[index] = null;
size--;
return oldValue;
}
index = hash2(hashCode);
if (key.equals(keyTable[index])) {
keyTable[index] = null;
V oldValue = valueTable[index];
valueTable[index] = null;
size--;
return oldValue;
}
index = hash3(hashCode);
if (key.equals(keyTable[index])) {
keyTable[index] = null;
V oldValue = valueTable[index];
valueTable[index] = null;
size--;
return oldValue;
}
return removeStash(key);
}
V removeStash (K key) {
K[] keyTable = this.keyTable;
for (int i = capacity, n = i + stashSize; i < n; i++) {
if (key.equals(keyTable[i])) {
V oldValue = valueTable[i];
removeStashIndex(i);
size--;
return oldValue;
}
}
return null;
}
void removeStashIndex (int index) {
// If the removed location was not last, move the last tuple to the removed location.
stashSize--;
int lastIndex = capacity + stashSize;
if (index < lastIndex) {
keyTable[index] = keyTable[lastIndex];
valueTable[index] = valueTable[lastIndex];
valueTable[lastIndex] = null;
} else
valueTable[index] = null;
}
/** Reduces the size of the backing arrays to be the specified capacity or less. If the capacity is already less, nothing is
* done. If the map contains more items than the specified capacity, the next highest power of two capacity is used instead. */
public void shrink (int maximumCapacity) {
if (maximumCapacity < 0) throw new IllegalArgumentException("maximumCapacity must be >= 0: " + maximumCapacity);
if (size > maximumCapacity) maximumCapacity = size;
if (capacity <= maximumCapacity) return;
maximumCapacity = nextPowerOfTwo(maximumCapacity);
resize(maximumCapacity);
}
/** Clears the map and reduces the size of the backing arrays to be the specified capacity if they are larger. */
public void clear (int maximumCapacity) {
if (capacity <= maximumCapacity) {
clear();
return;
}
size = 0;
resize(maximumCapacity);
}
public void clear () {
if (size == 0) return;
K[] keyTable = this.keyTable;
V[] valueTable = this.valueTable;
for (int i = capacity + stashSize; i-- > 0;) {
keyTable[i] = null;
valueTable[i] = null;
}
size = 0;
stashSize = 0;
}
/** Returns true if the specified value is in the map. Note this traverses the entire map and compares every value, which may be
* an expensive operation.
* @param identity If true, uses == to compare the specified value with values in the map. If false, uses
* {@link #equals(Object)}. */
public boolean containsValue (Object value, boolean identity) {
V[] valueTable = this.valueTable;
if (value == null) {
K[] keyTable = this.keyTable;
for (int i = capacity + stashSize; i-- > 0;)
if (keyTable[i] != null && valueTable[i] == null) return true;
} else if (identity) {
for (int i = capacity + stashSize; i-- > 0;)
if (valueTable[i] == value) return true;
} else {
for (int i = capacity + stashSize; i-- > 0;)
if (value.equals(valueTable[i])) return true;
}
return false;
}
public boolean containsKey (K key) {
int hashCode = key.hashCode();
int index = hashCode & mask;
if (!key.equals(keyTable[index])) {
index = hash2(hashCode);
if (!key.equals(keyTable[index])) {
index = hash3(hashCode);
if (!key.equals(keyTable[index])) return containsKeyStash(key);
}
}
return true;
}
private boolean containsKeyStash (K key) {
K[] keyTable = this.keyTable;
for (int i = capacity, n = i + stashSize; i < n; i++)
if (key.equals(keyTable[i])) return true;
return false;
}
/** Returns the key for the specified value, or null if it is not in the map. Note this traverses the entire map and compares
* every value, which may be an expensive operation.
* @param identity If true, uses == to compare the specified value with values in the map. If false, uses
* {@link #equals(Object)}. */
public K findKey (Object value, boolean identity) {
V[] valueTable = this.valueTable;
if (value == null) {
K[] keyTable = this.keyTable;
for (int i = capacity + stashSize; i-- > 0;)
if (keyTable[i] != null && valueTable[i] == null) return keyTable[i];
} else if (identity) {
for (int i = capacity + stashSize; i-- > 0;)
if (valueTable[i] == value) return keyTable[i];
} else {
for (int i = capacity + stashSize; i-- > 0;)
if (value.equals(valueTable[i])) return keyTable[i];
}
return null;
}
/** Increases the size of the backing array to accommodate the specified number of additional items. Useful before adding many
* items to avoid multiple backing array resizes. */
public void ensureCapacity (int additionalCapacity) {
int sizeNeeded = size + additionalCapacity;
if (sizeNeeded >= threshold) resize(nextPowerOfTwo((int)(sizeNeeded / loadFactor)));
}
+ @SuppressWarnings("unchecked")
private void resize (int newSize) {
int oldEndIndex = capacity + stashSize;
capacity = newSize;
threshold = (int)(newSize * loadFactor);
mask = newSize - 1;
hashShift = 31 - Integer.numberOfTrailingZeros(newSize);
stashCapacity = Math.max(3, (int)Math.ceil(Math.log(newSize)) * 2);
pushIterations = Math.max(Math.min(newSize, 8), (int)Math.sqrt(newSize) / 8);
K[] oldKeyTable = keyTable;
V[] oldValueTable = valueTable;
keyTable = (K[])new Object[newSize + stashCapacity];
valueTable = (V[])new Object[newSize + stashCapacity];
int oldSize = size;
size = 0;
stashSize = 0;
if (oldSize > 0) {
for (int i = 0; i < oldEndIndex; i++) {
K key = oldKeyTable[i];
if (key != null) putResize(key, oldValueTable[i]);
}
}
}
private int hash2 (int h) {
h *= PRIME2;
return (h ^ h >>> hashShift) & mask;
}
private int hash3 (int h) {
h *= PRIME3;
return (h ^ h >>> hashShift) & mask;
}
public String toString (String separator) {
return toString(separator, false);
}
public String toString () {
return toString(", ", true);
}
private String toString (String separator, boolean braces) {
if (size == 0) return braces ? "{}" : "";
StringBuilder buffer = new StringBuilder(32);
if (braces) buffer.append('{');
K[] keyTable = this.keyTable;
V[] valueTable = this.valueTable;
int i = keyTable.length;
while (i-- > 0) {
K key = keyTable[i];
if (key == null) continue;
buffer.append(key);
buffer.append('=');
buffer.append(valueTable[i]);
break;
}
while (i-- > 0) {
K key = keyTable[i];
if (key == null) continue;
buffer.append(separator);
buffer.append(key);
buffer.append('=');
buffer.append(valueTable[i]);
}
if (braces) buffer.append('}');
return buffer.toString();
}
}
|
dido/arcueid
|
a0689546b423742cad845214a2b103ac4efd6441
|
menv should now set the stack pointer properly
|
diff --git a/java/src/org/arcueidarc/nekoarc/vm/VirtualMachine.java b/java/src/org/arcueidarc/nekoarc/vm/VirtualMachine.java
index a36b671..99a3733 100644
--- a/java/src/org/arcueidarc/nekoarc/vm/VirtualMachine.java
+++ b/java/src/org/arcueidarc/nekoarc/vm/VirtualMachine.java
@@ -194,529 +194,534 @@ public class VirtualMachine implements Callable
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
new ENV(), // 0xca
new ENVR(), // 0xcb
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
};
private ObjectMap<Symbol, ArcObject> genv = new ObjectMap<Symbol, ArcObject>();
public VirtualMachine(int stacksize)
{
sp = bp = 0;
stack = new ArcObject[stacksize];
ip = 0;
code = null;
runnable = true;
env = Nil.NIL;
cont = Nil.NIL;
setAcc(Nil.NIL);
caller = new CallSync();
}
public void load(final byte[] instructions, int ip, final ArcObject[] literals)
{
this.code = instructions;
this.literals = literals;
this.ip = ip;
}
public void load(final byte[] instructions, int ip)
{
load(instructions, ip, null);
}
public void halt()
{
runnable = false;
}
public void nextI()
{
ip++;
}
/**
* Attempt to garbage collect the stack, after Richard A. Kelsey, "Tail Recursive Stack Disciplines for an Interpreter"
* Basically, the only things on the stack that are garbage collected are environments and continuations.
* The algorithm here works by copying all environments and continuations from the stack to the heap. When that's done it will move the stack pointer
* to the top of the stack.
* 1. Start with the environment register. Move that environment and all of its children to the heap.
* 2. Continue with the continuation register. Copy the current continuation into the heap.
* 3. Compact the stack by moving the remainder of the non-stack/non-continuation elements down.
*/
private void stackgc()
{
int[] deepest = {sp};
if (env instanceof Fixnum)
env = HeapEnv.fromStackEnv(this, env, deepest);
// If the current continuation is on the stack move it to the heap
if (cont instanceof Fixnum)
this.setCont(HeapContinuation.fromStackCont(this, cont, deepest));
// If all environments and continuations have been moved to the heap, we can now
// move all other stack elements down to the bottom.
for (int i=0; i<sp - bp; i++)
setStackIndex(i, stackIndex(bp + i));
sp = (sp - bp);
bp = 0;
}
public void push(ArcObject obj)
{
for (;;) {
try {
stack[sp++] = obj;
return;
} catch (ArrayIndexOutOfBoundsException e) {
// Restore sp to its old value before stack gc
sp--;
stackgc();
if (sp >= stack.length)
throw new NekoArcException("stack overflow");
}
}
}
public ArcObject pop()
{
return(stack[--sp]);
}
public void run()
throws NekoArcException
{
while (runnable) {
jmptbl[(int)code[ip++] & 0xff].invoke(this);
}
}
// Four-byte instruction arguments (most everything else). Little endian.
public int instArg()
{
long val = 0;
int data;
for (int i=0; i<4; i++) {
data = (((int)code[ip++]) & 0xff);
val |= data << i*8;
}
return((int)((val << 1) >> 1));
}
// one-byte instruction arguments (LDE/STE/ENV, etc.)
public byte smallInstArg()
{
return(code[ip++]);
}
public ArcObject getAcc()
{
return acc;
}
public void setAcc(ArcObject acc)
{
this.acc = acc;
}
public boolean runnable()
{
return(this.runnable);
}
public boolean setrunnable(boolean runstate)
{
this.runnable = runstate;
return(runstate);
}
public ArcObject literal(int offset)
{
return(literals[offset]);
}
public int getIP()
{
return ip;
}
public void setIP(int ip)
{
this.ip = ip;
}
public int getSP()
{
return(sp);
}
public void setSP(int sp)
{
this.sp = sp;
}
// add or replace a global binding
public ArcObject bind(Symbol sym, ArcObject binding)
{
genv.put(sym, binding);
return(binding);
}
public ArcObject value(Symbol sym)
{
if (!genv.containsKey(sym))
throw new NekoArcException("Unbound symbol " + sym);
return(genv.get(sym));
}
public int argc()
{
return(argc);
}
public int setargc(int ac)
{
return(argc = ac);
}
public void argcheck(int minarg, int maxarg)
{
if (argc() < minarg)
throw new NekoArcException("too few arguments, at least " + minarg + " required, " + argc() + " passed");
if (maxarg >= 0 && argc() > maxarg)
throw new NekoArcException("too many arguments, at most " + maxarg + " allowed, " + argc() + " passed");
}
public void argcheck(int arg)
{
argcheck(arg, arg);
}
/* Create an environment. If there is enough space on the stack, that environment will be there,
* if not, it will be created in the heap. */
public void mkenv(int prevsize, int extrasize)
{
// Do a check for the space on the stack. If there is not enough,
// make the environment in the heap */
if (sp + extrasize + 3 > stack.length) {
mkheapenv(prevsize, extrasize);
return;
}
// If there is enough space on the stack, create the environment there.
// Add the extra environment entries
for (int i=0; i<extrasize; i++)
push(Unbound.UNBOUND);
int count = prevsize + extrasize;
int envstart = sp - count;
/* Stack environments are basically Fixnum pointers into the stack. */
int envptr = sp;
push(Fixnum.get(envstart)); // envptr
push(Fixnum.get(count)); // envptr + 1
push(env); // envptr + 2
env = Fixnum.get(envptr);
bp = sp;
}
/** Create a new heap environment ab initio */
private void mkheapenv(int prevsize, int extrasize)
{
// First, convert what will become the parent environment to a heap environment if it is not already one
env = HeapEnv.fromStackEnv(this, env);
int envstart = sp - prevsize;
// Create new heap environment and copy the environment values from the stack into it
HeapEnv nenv = new HeapEnv(prevsize + extrasize, env);
for (int i=0; i<prevsize; i++)
nenv.setEnv(i, stackIndex(envstart + i));
// Fill in extra environment entries with UNBOUND
for (int i=prevsize; i<prevsize+extrasize; i++)
nenv.setEnv(i, Unbound.UNBOUND);
bp = sp;
env = nenv;
}
/** move current environment to heap if needed */
public ArcObject heapenv()
{
env = HeapEnv.fromStackEnv(this, env);
return(env);
}
private ArcObject nextenv()
{
if (env.is(Nil.NIL))
return(Nil.NIL);
if (env instanceof Fixnum) {
int index = (int)((Fixnum)env).fixnum;
return(stackIndex(index+2));
}
HeapEnv e = (HeapEnv)env;
return(e.prevEnv());
}
private ArcObject findenv(int depth)
{
ArcObject cenv = env;
while (depth-- > 0 && !cenv.is(Nil.NIL)) {
if (cenv instanceof Fixnum) {
int index = (int)((Fixnum)cenv).fixnum;
cenv = stackIndex(index+2);
} else {
HeapEnv e = (HeapEnv)cenv;
cenv = e.prevEnv();
}
}
return(cenv);
}
public ArcObject getenv(int depth, int index)
{
ArcObject cenv = findenv(depth);
if (cenv == Nil.NIL)
throw new NekoArcException("environment depth exceeded");
if (cenv instanceof Fixnum) {
int si = (int)((Fixnum)cenv).fixnum;
int start = (int)((Fixnum)stackIndex(si)).fixnum;
int size = (int)((Fixnum)stackIndex(si+1)).fixnum;
if (index > size)
throw new NekoArcException("stack environment index exceeded");
return(stackIndex(start+index));
}
return(((HeapEnv)cenv).getEnv(index));
}
public ArcObject setenv(int depth, int index, ArcObject value)
{
ArcObject cenv = findenv(depth);
if (cenv == Nil.NIL)
throw new NekoArcException("environment depth exceeded");
if (cenv instanceof Fixnum) {
int si = (int)((Fixnum)cenv).fixnum;
int start = (int)((Fixnum)stackIndex(si)).fixnum;
int size = (int)((Fixnum)stackIndex(si+1)).fixnum;
if (index > size)
throw new NekoArcException("stack environment index exceeded");
return(setStackIndex(start+index, value));
}
return(((HeapEnv)cenv).setEnv(index,value));
}
public ArcObject stackIndex(int index)
{
return(stack[index]);
}
public ArcObject setStackIndex(int index, ArcObject value)
{
return(stack[index] = value);
}
public void stackcheck(int required, final String message)
{
if (sp + required > stack.length) {
// Try to do stack gc first. If it fails, nothing for it
stackgc();
if (sp + required > stack.length)
throw new NekoArcException(message);
}
}
// Make a continuation on the stack. The new continuation is saved in the continuation register.
public void makecont(int ipoffset)
{
stackcheck(4, "stack overflow while creating continuation");
int newip = ip + ipoffset;
push(Fixnum.get(newip));
push(Fixnum.get(bp));
push(env);
push(cont);
cont = Fixnum.get(sp);
bp = sp;
}
public void restorecont()
{
restorecont(this);
}
// Restore continuation
public void restorecont(Callable caller)
{
if (cont instanceof Fixnum) {
sp = (int)((Fixnum)cont).fixnum;
cont = pop();
setenvreg(pop());
setBP((int)((Fixnum)pop()).fixnum);
setIP((int)((Fixnum)pop()).fixnum);
} else if (cont instanceof Continuation) {
Continuation ct = (Continuation)cont;
ct.restore(this, caller);
} else if (cont.is(Nil.NIL)) {
// If we have no continuation, that was an attempt to return from the topmost
// level and we should halt the machine.
halt();
} else {
throw new NekoArcException("invalid continuation");
}
}
public void setenvreg(ArcObject env)
{
this.env = env;
}
public int getBP()
{
return bp;
}
public void setBP(int bp)
{
this.bp = bp;
}
public ArcObject getCont()
{
return cont;
}
public void setCont(ArcObject cont)
{
this.cont = cont;
}
@Override
public CallSync sync()
{
return(caller);
}
/**
* Move n elements from the top of stack, overwriting the current
* environment. Points the stack pointer to just above the last
* element moved. Does not do this if current environment is on
* the heap. It will, in either case, set the environment register to
* the parent environment (possibly leaving the heap environment as
* garbage to be collected)
*
* This is essentially used to support tail calls and tail recursion.
* When this mechanism is used, the new arguments are on the stack,
* over the previous environment. It will move all of the new arguments
* onto the old environment and adjust the stack pointer appropriately.
* When control is transferred to the tail called function the call
* to mkenv will turn the stuff on the stack into a new environment.
*/
public void menv(int n)
{
// do nothing if we have no env
if (env.is(Nil.NIL))
return;
ArcObject parentenv = nextenv();
- // We only bother if the present environment and its parent
- // (which is to be superseded) are both on the stack.
+ // We only bother if the current environment, which is to be
+ // superseded, is on the stack. We move the n values previously
+ // pushed to the location of the current environment,
+ // overwriting it, and we set the stack pointer to the point
+ // just after.
if (env instanceof Fixnum) {
// Destination is the previous environment
int si = (int)((Fixnum)env).fixnum;
int dest = (int)((Fixnum)stackIndex(si)).fixnum;
// Source is the values on the stack
- int src = sp - n - 1;
+ int src = sp - n;
System.arraycopy(stack, src, stack, dest, n);
- // new stack pointer
+ // new stack pointer has to point to just after moved stuff
+ setSP(dest + n);
}
// If the current environment was on the heap, none of this black
// magic needs to be done. It is enough to just set the environment
- // register to point to the parent environment.
+ // register to point to the parent environment (the old environment
+ // thereby becoming garbage unless part of a continuation).
setenvreg(parentenv);
}
}
|
dido/arcueid
|
8c537f8abe85bd0b892302ec561e656f1ca9339e
|
menv instruction implemented
|
diff --git a/java/src/org/arcueidarc/nekoarc/vm/instruction/MENV.java b/java/src/org/arcueidarc/nekoarc/vm/instruction/MENV.java
index 5b4b0ef..01028fb 100644
--- a/java/src/org/arcueidarc/nekoarc/vm/instruction/MENV.java
+++ b/java/src/org/arcueidarc/nekoarc/vm/instruction/MENV.java
@@ -1,15 +1,15 @@
package org.arcueidarc.nekoarc.vm.instruction;
import org.arcueidarc.nekoarc.NekoArcException;
import org.arcueidarc.nekoarc.vm.Instruction;
import org.arcueidarc.nekoarc.vm.VirtualMachine;
public class MENV implements Instruction {
@Override
- public void invoke(VirtualMachine vm) throws NekoArcException {
- // TODO Auto-generated method stub
-
+ public void invoke(VirtualMachine vm) throws NekoArcException
+ {
+ vm.menv((int)(vm.smallInstArg() & 0xff));
}
}
|
dido/arcueid
|
f41ff9696cf03dee28e46de9c63326d1d9053179
|
remove DUP and SPL instructions, and new method for menv added
|
diff --git a/java/src/org/arcueidarc/nekoarc/vm/VirtualMachine.java b/java/src/org/arcueidarc/nekoarc/vm/VirtualMachine.java
index e132798..a36b671 100644
--- a/java/src/org/arcueidarc/nekoarc/vm/VirtualMachine.java
+++ b/java/src/org/arcueidarc/nekoarc/vm/VirtualMachine.java
@@ -1,670 +1,722 @@
package org.arcueidarc.nekoarc.vm;
import org.arcueidarc.nekoarc.Continuation;
import org.arcueidarc.nekoarc.HeapContinuation;
import org.arcueidarc.nekoarc.HeapEnv;
import org.arcueidarc.nekoarc.NekoArcException;
import org.arcueidarc.nekoarc.Nil;
import org.arcueidarc.nekoarc.Unbound;
import org.arcueidarc.nekoarc.types.ArcObject;
import org.arcueidarc.nekoarc.types.Fixnum;
import org.arcueidarc.nekoarc.types.Symbol;
import org.arcueidarc.nekoarc.util.CallSync;
import org.arcueidarc.nekoarc.util.Callable;
import org.arcueidarc.nekoarc.util.ObjectMap;
import org.arcueidarc.nekoarc.vm.instruction.*;
public class VirtualMachine implements Callable
{
private int sp; // stack pointer
private int bp; // base pointer
private ArcObject env; // environment pointer
private ArcObject cont; // continuation pointer
private ArcObject[] stack; // stack
private final CallSync caller;
private int ip; // instruction pointer
private byte[] code;
private boolean runnable;
private ArcObject acc; // accumulator
private ArcObject[] literals;
private int argc; // argument counter for current function
private static final INVALID NOINST = new INVALID();
private static final Instruction[] jmptbl = {
new NOP(), // 0x00
new PUSH(), // 0x01
new POP(), // 0x02
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
new RET(), // 0x0d
NOINST,
NOINST,
NOINST,
new NO(), // 0x11
new TRUE(), // 0x12
new NIL(), // 0x13
new HLT(), // 0x14
new ADD(), // 0x15
new SUB(), // 0x16
new MUL(), // 0x17
new DIV(), // 0x18
new CONS(), // 0x19
new CAR(), // 0x1a
new CDR(), // 0x1b
new SCAR(), // 0x1c
new SCDR(), // 0x1d
NOINST,
new IS(), // 0x1f
NOINST,
NOINST,
- new DUP(), // 0x22
+ NOINST, // used to be DUP, 0x22
NOINST, // 0x23
new CONSR(), // 0x24
NOINST,
new DCAR(), // 0x26
new DCDR(), // 0x27
- new SPL(), // 0x28
+ NOINST, // used to be SPL, 0x28
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
new LDL(), // 0x43
new LDI(), // 0x44
new LDG(), // 0x45
new STG(), // 0x46
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
new APPLY(), // 0x4c
new CLS(), // 0x4d,
new JMP(), // 0x4e
new JT(), // 0x4f
new JF(), // 0x50
new JBND(), // 0x51
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
new MENV(), // 0x65
NOINST,
NOINST,
NOINST,
new LDE0(), // 0x69
new STE0(), // 0x6a
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
new LDE(), // 0x87
new STE(), // 0x88
new CONT(), // 0x89
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
new ENV(), // 0xca
new ENVR(), // 0xcb
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
};
private ObjectMap<Symbol, ArcObject> genv = new ObjectMap<Symbol, ArcObject>();
public VirtualMachine(int stacksize)
{
sp = bp = 0;
stack = new ArcObject[stacksize];
ip = 0;
code = null;
runnable = true;
env = Nil.NIL;
cont = Nil.NIL;
setAcc(Nil.NIL);
caller = new CallSync();
}
public void load(final byte[] instructions, int ip, final ArcObject[] literals)
{
this.code = instructions;
this.literals = literals;
this.ip = ip;
}
public void load(final byte[] instructions, int ip)
{
load(instructions, ip, null);
}
public void halt()
{
runnable = false;
}
public void nextI()
{
ip++;
}
/**
* Attempt to garbage collect the stack, after Richard A. Kelsey, "Tail Recursive Stack Disciplines for an Interpreter"
* Basically, the only things on the stack that are garbage collected are environments and continuations.
* The algorithm here works by copying all environments and continuations from the stack to the heap. When that's done it will move the stack pointer
* to the top of the stack.
* 1. Start with the environment register. Move that environment and all of its children to the heap.
* 2. Continue with the continuation register. Copy the current continuation into the heap.
* 3. Compact the stack by moving the remainder of the non-stack/non-continuation elements down.
*/
private void stackgc()
{
int[] deepest = {sp};
if (env instanceof Fixnum)
env = HeapEnv.fromStackEnv(this, env, deepest);
// If the current continuation is on the stack move it to the heap
if (cont instanceof Fixnum)
this.setCont(HeapContinuation.fromStackCont(this, cont, deepest));
// If all environments and continuations have been moved to the heap, we can now
// move all other stack elements down to the bottom.
for (int i=0; i<sp - bp; i++)
setStackIndex(i, stackIndex(bp + i));
sp = (sp - bp);
bp = 0;
}
public void push(ArcObject obj)
{
for (;;) {
try {
stack[sp++] = obj;
return;
} catch (ArrayIndexOutOfBoundsException e) {
// Restore sp to its old value before stack gc
sp--;
stackgc();
if (sp >= stack.length)
throw new NekoArcException("stack overflow");
}
}
}
public ArcObject pop()
{
return(stack[--sp]);
}
public void run()
throws NekoArcException
{
while (runnable) {
jmptbl[(int)code[ip++] & 0xff].invoke(this);
}
}
// Four-byte instruction arguments (most everything else). Little endian.
public int instArg()
{
long val = 0;
int data;
for (int i=0; i<4; i++) {
data = (((int)code[ip++]) & 0xff);
val |= data << i*8;
}
return((int)((val << 1) >> 1));
}
// one-byte instruction arguments (LDE/STE/ENV, etc.)
public byte smallInstArg()
{
return(code[ip++]);
}
public ArcObject getAcc()
{
return acc;
}
public void setAcc(ArcObject acc)
{
this.acc = acc;
}
public boolean runnable()
{
return(this.runnable);
}
public boolean setrunnable(boolean runstate)
{
this.runnable = runstate;
return(runstate);
}
public ArcObject literal(int offset)
{
return(literals[offset]);
}
public int getIP()
{
return ip;
}
public void setIP(int ip)
{
this.ip = ip;
}
public int getSP()
{
return(sp);
}
public void setSP(int sp)
{
this.sp = sp;
}
// add or replace a global binding
public ArcObject bind(Symbol sym, ArcObject binding)
{
genv.put(sym, binding);
return(binding);
}
public ArcObject value(Symbol sym)
{
if (!genv.containsKey(sym))
throw new NekoArcException("Unbound symbol " + sym);
return(genv.get(sym));
}
public int argc()
{
return(argc);
}
public int setargc(int ac)
{
return(argc = ac);
}
public void argcheck(int minarg, int maxarg)
{
if (argc() < minarg)
throw new NekoArcException("too few arguments, at least " + minarg + " required, " + argc() + " passed");
if (maxarg >= 0 && argc() > maxarg)
throw new NekoArcException("too many arguments, at most " + maxarg + " allowed, " + argc() + " passed");
}
public void argcheck(int arg)
{
argcheck(arg, arg);
}
/* Create an environment. If there is enough space on the stack, that environment will be there,
* if not, it will be created in the heap. */
public void mkenv(int prevsize, int extrasize)
{
+ // Do a check for the space on the stack. If there is not enough,
+ // make the environment in the heap */
if (sp + extrasize + 3 > stack.length) {
mkheapenv(prevsize, extrasize);
return;
}
// If there is enough space on the stack, create the environment there.
// Add the extra environment entries
for (int i=0; i<extrasize; i++)
push(Unbound.UNBOUND);
int count = prevsize + extrasize;
int envstart = sp - count;
/* Stack environments are basically Fixnum pointers into the stack. */
int envptr = sp;
push(Fixnum.get(envstart)); // envptr
push(Fixnum.get(count)); // envptr + 1
push(env); // envptr + 2
env = Fixnum.get(envptr);
bp = sp;
}
/** Create a new heap environment ab initio */
private void mkheapenv(int prevsize, int extrasize)
{
// First, convert what will become the parent environment to a heap environment if it is not already one
env = HeapEnv.fromStackEnv(this, env);
int envstart = sp - prevsize;
// Create new heap environment and copy the environment values from the stack into it
HeapEnv nenv = new HeapEnv(prevsize + extrasize, env);
for (int i=0; i<prevsize; i++)
nenv.setEnv(i, stackIndex(envstart + i));
// Fill in extra environment entries with UNBOUND
for (int i=prevsize; i<prevsize+extrasize; i++)
nenv.setEnv(i, Unbound.UNBOUND);
bp = sp;
env = nenv;
}
/** move current environment to heap if needed */
public ArcObject heapenv()
{
env = HeapEnv.fromStackEnv(this, env);
return(env);
}
+ private ArcObject nextenv()
+ {
+ if (env.is(Nil.NIL))
+ return(Nil.NIL);
+ if (env instanceof Fixnum) {
+ int index = (int)((Fixnum)env).fixnum;
+ return(stackIndex(index+2));
+ }
+ HeapEnv e = (HeapEnv)env;
+ return(e.prevEnv());
+ }
+
private ArcObject findenv(int depth)
{
ArcObject cenv = env;
while (depth-- > 0 && !cenv.is(Nil.NIL)) {
if (cenv instanceof Fixnum) {
int index = (int)((Fixnum)cenv).fixnum;
cenv = stackIndex(index+2);
} else {
HeapEnv e = (HeapEnv)cenv;
cenv = e.prevEnv();
}
}
return(cenv);
}
public ArcObject getenv(int depth, int index)
{
ArcObject cenv = findenv(depth);
if (cenv == Nil.NIL)
throw new NekoArcException("environment depth exceeded");
if (cenv instanceof Fixnum) {
int si = (int)((Fixnum)cenv).fixnum;
int start = (int)((Fixnum)stackIndex(si)).fixnum;
int size = (int)((Fixnum)stackIndex(si+1)).fixnum;
if (index > size)
throw new NekoArcException("stack environment index exceeded");
return(stackIndex(start+index));
}
return(((HeapEnv)cenv).getEnv(index));
}
public ArcObject setenv(int depth, int index, ArcObject value)
{
ArcObject cenv = findenv(depth);
if (cenv == Nil.NIL)
throw new NekoArcException("environment depth exceeded");
if (cenv instanceof Fixnum) {
int si = (int)((Fixnum)cenv).fixnum;
int start = (int)((Fixnum)stackIndex(si)).fixnum;
int size = (int)((Fixnum)stackIndex(si+1)).fixnum;
if (index > size)
throw new NekoArcException("stack environment index exceeded");
return(setStackIndex(start+index, value));
}
return(((HeapEnv)cenv).setEnv(index,value));
}
public ArcObject stackIndex(int index)
{
return(stack[index]);
}
public ArcObject setStackIndex(int index, ArcObject value)
{
return(stack[index] = value);
}
public void stackcheck(int required, final String message)
{
if (sp + required > stack.length) {
// Try to do stack gc first. If it fails, nothing for it
stackgc();
if (sp + required > stack.length)
throw new NekoArcException(message);
}
}
// Make a continuation on the stack. The new continuation is saved in the continuation register.
public void makecont(int ipoffset)
{
stackcheck(4, "stack overflow while creating continuation");
int newip = ip + ipoffset;
push(Fixnum.get(newip));
push(Fixnum.get(bp));
push(env);
push(cont);
cont = Fixnum.get(sp);
bp = sp;
}
public void restorecont()
{
restorecont(this);
}
// Restore continuation
public void restorecont(Callable caller)
{
if (cont instanceof Fixnum) {
sp = (int)((Fixnum)cont).fixnum;
cont = pop();
setenvreg(pop());
setBP((int)((Fixnum)pop()).fixnum);
setIP((int)((Fixnum)pop()).fixnum);
} else if (cont instanceof Continuation) {
Continuation ct = (Continuation)cont;
ct.restore(this, caller);
} else if (cont.is(Nil.NIL)) {
// If we have no continuation, that was an attempt to return from the topmost
// level and we should halt the machine.
halt();
} else {
throw new NekoArcException("invalid continuation");
}
}
public void setenvreg(ArcObject env)
{
this.env = env;
}
public int getBP()
{
return bp;
}
public void setBP(int bp)
{
this.bp = bp;
}
public ArcObject getCont()
{
return cont;
}
public void setCont(ArcObject cont)
{
this.cont = cont;
}
@Override
public CallSync sync()
{
return(caller);
}
+
+ /**
+ * Move n elements from the top of stack, overwriting the current
+ * environment. Points the stack pointer to just above the last
+ * element moved. Does not do this if current environment is on
+ * the heap. It will, in either case, set the environment register to
+ * the parent environment (possibly leaving the heap environment as
+ * garbage to be collected)
+ *
+ * This is essentially used to support tail calls and tail recursion.
+ * When this mechanism is used, the new arguments are on the stack,
+ * over the previous environment. It will move all of the new arguments
+ * onto the old environment and adjust the stack pointer appropriately.
+ * When control is transferred to the tail called function the call
+ * to mkenv will turn the stuff on the stack into a new environment.
+ */
+ public void menv(int n)
+ {
+ // do nothing if we have no env
+ if (env.is(Nil.NIL))
+ return;
+ ArcObject parentenv = nextenv();
+ // We only bother if the present environment and its parent
+ // (which is to be superseded) are both on the stack.
+ if (env instanceof Fixnum) {
+ // Destination is the previous environment
+ int si = (int)((Fixnum)env).fixnum;
+ int dest = (int)((Fixnum)stackIndex(si)).fixnum;
+ // Source is the values on the stack
+ int src = sp - n - 1;
+ System.arraycopy(stack, src, stack, dest, n);
+ // new stack pointer
+ }
+ // If the current environment was on the heap, none of this black
+ // magic needs to be done. It is enough to just set the environment
+ // register to point to the parent environment.
+ setenvreg(parentenv);
+ }
}
|
dido/arcueid
|
edcca0bf6ed0173717f04f057d252d14a3434929
|
remove note that this is a stub
|
diff --git a/java/src/org/arcueidarc/nekoarc/vm/instruction/DCDR.java b/java/src/org/arcueidarc/nekoarc/vm/instruction/DCDR.java
index e3db79c..37f2025 100644
--- a/java/src/org/arcueidarc/nekoarc/vm/instruction/DCDR.java
+++ b/java/src/org/arcueidarc/nekoarc/vm/instruction/DCDR.java
@@ -1,21 +1,20 @@
package org.arcueidarc.nekoarc.vm.instruction;
import org.arcueidarc.nekoarc.NekoArcException;
import org.arcueidarc.nekoarc.Nil;
import org.arcueidarc.nekoarc.Unbound;
import org.arcueidarc.nekoarc.vm.Instruction;
import org.arcueidarc.nekoarc.vm.VirtualMachine;
public class DCDR implements Instruction
{
@Override
public void invoke(VirtualMachine vm) throws NekoArcException
{
- // TODO Auto-generated method stub
if (vm.getAcc().is(Nil.NIL) || vm.getAcc().is(Unbound.UNBOUND))
vm.setAcc(Unbound.UNBOUND);
else
vm.setAcc(vm.getAcc().cdr());
}
}
|
dido/arcueid
|
0edb1f6deb9678447da936d52f963270f1d5a247
|
remove method stub comment (as it's already implemented)
|
diff --git a/java/src/org/arcueidarc/nekoarc/vm/instruction/DCDR.java b/java/src/org/arcueidarc/nekoarc/vm/instruction/DCDR.java
index e3db79c..37f2025 100644
--- a/java/src/org/arcueidarc/nekoarc/vm/instruction/DCDR.java
+++ b/java/src/org/arcueidarc/nekoarc/vm/instruction/DCDR.java
@@ -1,21 +1,20 @@
package org.arcueidarc.nekoarc.vm.instruction;
import org.arcueidarc.nekoarc.NekoArcException;
import org.arcueidarc.nekoarc.Nil;
import org.arcueidarc.nekoarc.Unbound;
import org.arcueidarc.nekoarc.vm.Instruction;
import org.arcueidarc.nekoarc.vm.VirtualMachine;
public class DCDR implements Instruction
{
@Override
public void invoke(VirtualMachine vm) throws NekoArcException
{
- // TODO Auto-generated method stub
if (vm.getAcc().is(Nil.NIL) || vm.getAcc().is(Unbound.UNBOUND))
vm.setAcc(Unbound.UNBOUND);
else
vm.setAcc(vm.getAcc().cdr());
}
}
|
dido/arcueid
|
77372d2aa5cb2a221fa9966eeef36f41d64975f9
|
comments describing function added
|
diff --git a/java/test/org/arcueidarc/nekoarc/functions/CCCtest.java b/java/test/org/arcueidarc/nekoarc/functions/CCCtest.java
index b1a2d5d..6bf4a91 100644
--- a/java/test/org/arcueidarc/nekoarc/functions/CCCtest.java
+++ b/java/test/org/arcueidarc/nekoarc/functions/CCCtest.java
@@ -1,15 +1,22 @@
package org.arcueidarc.nekoarc.functions;
import static org.junit.Assert.*;
import org.junit.Test;
public class CCCtest
{
@Test
public void test()
{
+ // A rather contrived use of ccc to do something sort of useful as a test. (fn (treat lst) (ccc (fn (return) (each x lst (treat x return))))
+ // Apply with something like (fn (x return) (if (is x 10) (return (+ x 1)))) and '(1 2 3 10 5). Should produce 11.
+ // env 2 0 0; ldl 0 [inner fn]; cls; push; ldl 1 [ccc]; apply 1; ret
+ // [inner fn]
+ // env 1 0 0; L0: lde 1 1; cdr; jt L1; ret; L1: lde 1 1; car; push; lde0 0; push; lde 1 0; apply 2; jmp L0;
+ // [treat]
+ // env 2 0 0; lde0 0; push; ldl 10; is; jt L0; ret; lde0 0; push; ldl 1; add; push; lde0 1; apply 1; ret
fail("Not yet implemented");
}
}
|
dido/arcueid
|
fdfca3085423fb9ad70fa2719d94a3404cd13ba6
|
stack garbage collection cleanup
|
diff --git a/java/src/org/arcueidarc/nekoarc/vm/VirtualMachine.java b/java/src/org/arcueidarc/nekoarc/vm/VirtualMachine.java
index 282055e..e132798 100644
--- a/java/src/org/arcueidarc/nekoarc/vm/VirtualMachine.java
+++ b/java/src/org/arcueidarc/nekoarc/vm/VirtualMachine.java
@@ -1,675 +1,670 @@
package org.arcueidarc.nekoarc.vm;
import org.arcueidarc.nekoarc.Continuation;
import org.arcueidarc.nekoarc.HeapContinuation;
import org.arcueidarc.nekoarc.HeapEnv;
import org.arcueidarc.nekoarc.NekoArcException;
import org.arcueidarc.nekoarc.Nil;
import org.arcueidarc.nekoarc.Unbound;
import org.arcueidarc.nekoarc.types.ArcObject;
import org.arcueidarc.nekoarc.types.Fixnum;
import org.arcueidarc.nekoarc.types.Symbol;
import org.arcueidarc.nekoarc.util.CallSync;
import org.arcueidarc.nekoarc.util.Callable;
import org.arcueidarc.nekoarc.util.ObjectMap;
import org.arcueidarc.nekoarc.vm.instruction.*;
public class VirtualMachine implements Callable
{
private int sp; // stack pointer
private int bp; // base pointer
private ArcObject env; // environment pointer
private ArcObject cont; // continuation pointer
private ArcObject[] stack; // stack
private final CallSync caller;
private int ip; // instruction pointer
private byte[] code;
private boolean runnable;
private ArcObject acc; // accumulator
private ArcObject[] literals;
private int argc; // argument counter for current function
private static final INVALID NOINST = new INVALID();
private static final Instruction[] jmptbl = {
new NOP(), // 0x00
new PUSH(), // 0x01
new POP(), // 0x02
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
new RET(), // 0x0d
NOINST,
NOINST,
NOINST,
new NO(), // 0x11
new TRUE(), // 0x12
new NIL(), // 0x13
new HLT(), // 0x14
new ADD(), // 0x15
new SUB(), // 0x16
new MUL(), // 0x17
new DIV(), // 0x18
new CONS(), // 0x19
new CAR(), // 0x1a
new CDR(), // 0x1b
new SCAR(), // 0x1c
new SCDR(), // 0x1d
NOINST,
new IS(), // 0x1f
NOINST,
NOINST,
new DUP(), // 0x22
NOINST, // 0x23
new CONSR(), // 0x24
NOINST,
new DCAR(), // 0x26
new DCDR(), // 0x27
new SPL(), // 0x28
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
new LDL(), // 0x43
new LDI(), // 0x44
new LDG(), // 0x45
new STG(), // 0x46
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
new APPLY(), // 0x4c
new CLS(), // 0x4d,
new JMP(), // 0x4e
new JT(), // 0x4f
new JF(), // 0x50
new JBND(), // 0x51
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
new MENV(), // 0x65
NOINST,
NOINST,
NOINST,
new LDE0(), // 0x69
new STE0(), // 0x6a
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
new LDE(), // 0x87
new STE(), // 0x88
new CONT(), // 0x89
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
new ENV(), // 0xca
new ENVR(), // 0xcb
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
};
private ObjectMap<Symbol, ArcObject> genv = new ObjectMap<Symbol, ArcObject>();
public VirtualMachine(int stacksize)
{
sp = bp = 0;
stack = new ArcObject[stacksize];
ip = 0;
code = null;
runnable = true;
env = Nil.NIL;
cont = Nil.NIL;
setAcc(Nil.NIL);
caller = new CallSync();
}
public void load(final byte[] instructions, int ip, final ArcObject[] literals)
{
this.code = instructions;
this.literals = literals;
this.ip = ip;
}
public void load(final byte[] instructions, int ip)
{
load(instructions, ip, null);
}
public void halt()
{
runnable = false;
}
public void nextI()
{
ip++;
}
/**
* Attempt to garbage collect the stack, after Richard A. Kelsey, "Tail Recursive Stack Disciplines for an Interpreter"
* Basically, the only things on the stack that are garbage collected are environments and continuations.
* The algorithm here works by copying all environments and continuations from the stack to the heap. When that's done it will move the stack pointer
* to the top of the stack.
* 1. Start with the environment register. Move that environment and all of its children to the heap.
* 2. Continue with the continuation register. Copy the current continuation into the heap.
- * 3. Compact the stack by moving the remainder of the non-stack/non-continuation elements to the heap.
+ * 3. Compact the stack by moving the remainder of the non-stack/non-continuation elements down.
*/
private void stackgc()
{
int[] deepest = {sp};
-
if (env instanceof Fixnum)
env = HeapEnv.fromStackEnv(this, env, deepest);
// If the current continuation is on the stack move it to the heap
if (cont instanceof Fixnum)
this.setCont(HeapContinuation.fromStackCont(this, cont, deepest));
- int stackbottom = deepest[0];
- // Garbage collection failed to produce memory
- if (stackbottom < 0 || stackbottom > stack.length || stackbottom == sp)
- return;
-
- // move what we can of the used portion of the stack to the lowest part of the stack we can reach.
+ // If all environments and continuations have been moved to the heap, we can now
+ // move all other stack elements down to the bottom.
for (int i=0; i<sp - bp; i++)
- setStackIndex(stackbottom + i, stackIndex(bp + i));
- sp = stackbottom + (sp - bp);
- bp = stackbottom;
+ setStackIndex(i, stackIndex(bp + i));
+ sp = (sp - bp);
+ bp = 0;
}
public void push(ArcObject obj)
{
for (;;) {
try {
stack[sp++] = obj;
return;
} catch (ArrayIndexOutOfBoundsException e) {
// Restore sp to its old value before stack gc
sp--;
stackgc();
if (sp >= stack.length)
throw new NekoArcException("stack overflow");
}
}
}
public ArcObject pop()
{
return(stack[--sp]);
}
public void run()
throws NekoArcException
{
while (runnable) {
jmptbl[(int)code[ip++] & 0xff].invoke(this);
}
}
// Four-byte instruction arguments (most everything else). Little endian.
public int instArg()
{
long val = 0;
int data;
for (int i=0; i<4; i++) {
data = (((int)code[ip++]) & 0xff);
val |= data << i*8;
}
return((int)((val << 1) >> 1));
}
// one-byte instruction arguments (LDE/STE/ENV, etc.)
public byte smallInstArg()
{
return(code[ip++]);
}
public ArcObject getAcc()
{
return acc;
}
public void setAcc(ArcObject acc)
{
this.acc = acc;
}
public boolean runnable()
{
return(this.runnable);
}
public boolean setrunnable(boolean runstate)
{
this.runnable = runstate;
return(runstate);
}
public ArcObject literal(int offset)
{
return(literals[offset]);
}
public int getIP()
{
return ip;
}
public void setIP(int ip)
{
this.ip = ip;
}
public int getSP()
{
return(sp);
}
public void setSP(int sp)
{
this.sp = sp;
}
// add or replace a global binding
public ArcObject bind(Symbol sym, ArcObject binding)
{
genv.put(sym, binding);
return(binding);
}
public ArcObject value(Symbol sym)
{
if (!genv.containsKey(sym))
throw new NekoArcException("Unbound symbol " + sym);
return(genv.get(sym));
}
public int argc()
{
return(argc);
}
public int setargc(int ac)
{
return(argc = ac);
}
public void argcheck(int minarg, int maxarg)
{
if (argc() < minarg)
throw new NekoArcException("too few arguments, at least " + minarg + " required, " + argc() + " passed");
if (maxarg >= 0 && argc() > maxarg)
throw new NekoArcException("too many arguments, at most " + maxarg + " allowed, " + argc() + " passed");
}
public void argcheck(int arg)
{
argcheck(arg, arg);
}
/* Create an environment. If there is enough space on the stack, that environment will be there,
* if not, it will be created in the heap. */
public void mkenv(int prevsize, int extrasize)
{
if (sp + extrasize + 3 > stack.length) {
mkheapenv(prevsize, extrasize);
return;
}
// If there is enough space on the stack, create the environment there.
// Add the extra environment entries
for (int i=0; i<extrasize; i++)
push(Unbound.UNBOUND);
int count = prevsize + extrasize;
int envstart = sp - count;
/* Stack environments are basically Fixnum pointers into the stack. */
int envptr = sp;
push(Fixnum.get(envstart)); // envptr
push(Fixnum.get(count)); // envptr + 1
push(env); // envptr + 2
env = Fixnum.get(envptr);
bp = sp;
}
/** Create a new heap environment ab initio */
private void mkheapenv(int prevsize, int extrasize)
{
// First, convert what will become the parent environment to a heap environment if it is not already one
env = HeapEnv.fromStackEnv(this, env);
int envstart = sp - prevsize;
// Create new heap environment and copy the environment values from the stack into it
HeapEnv nenv = new HeapEnv(prevsize + extrasize, env);
for (int i=0; i<prevsize; i++)
nenv.setEnv(i, stackIndex(envstart + i));
// Fill in extra environment entries with UNBOUND
for (int i=prevsize; i<prevsize+extrasize; i++)
nenv.setEnv(i, Unbound.UNBOUND);
bp = sp;
env = nenv;
}
/** move current environment to heap if needed */
public ArcObject heapenv()
{
env = HeapEnv.fromStackEnv(this, env);
return(env);
}
private ArcObject findenv(int depth)
{
ArcObject cenv = env;
while (depth-- > 0 && !cenv.is(Nil.NIL)) {
if (cenv instanceof Fixnum) {
int index = (int)((Fixnum)cenv).fixnum;
cenv = stackIndex(index+2);
} else {
HeapEnv e = (HeapEnv)cenv;
cenv = e.prevEnv();
}
}
return(cenv);
}
public ArcObject getenv(int depth, int index)
{
ArcObject cenv = findenv(depth);
if (cenv == Nil.NIL)
throw new NekoArcException("environment depth exceeded");
if (cenv instanceof Fixnum) {
int si = (int)((Fixnum)cenv).fixnum;
int start = (int)((Fixnum)stackIndex(si)).fixnum;
int size = (int)((Fixnum)stackIndex(si+1)).fixnum;
if (index > size)
throw new NekoArcException("stack environment index exceeded");
return(stackIndex(start+index));
}
return(((HeapEnv)cenv).getEnv(index));
}
public ArcObject setenv(int depth, int index, ArcObject value)
{
ArcObject cenv = findenv(depth);
if (cenv == Nil.NIL)
throw new NekoArcException("environment depth exceeded");
if (cenv instanceof Fixnum) {
int si = (int)((Fixnum)cenv).fixnum;
int start = (int)((Fixnum)stackIndex(si)).fixnum;
int size = (int)((Fixnum)stackIndex(si+1)).fixnum;
if (index > size)
throw new NekoArcException("stack environment index exceeded");
return(setStackIndex(start+index, value));
}
return(((HeapEnv)cenv).setEnv(index,value));
}
public ArcObject stackIndex(int index)
{
return(stack[index]);
}
public ArcObject setStackIndex(int index, ArcObject value)
{
return(stack[index] = value);
}
public void stackcheck(int required, final String message)
{
if (sp + required > stack.length) {
// Try to do stack gc first. If it fails, nothing for it
stackgc();
if (sp + required > stack.length)
throw new NekoArcException(message);
}
}
// Make a continuation on the stack. The new continuation is saved in the continuation register.
public void makecont(int ipoffset)
{
stackcheck(4, "stack overflow while creating continuation");
int newip = ip + ipoffset;
push(Fixnum.get(newip));
push(Fixnum.get(bp));
push(env);
push(cont);
cont = Fixnum.get(sp);
bp = sp;
}
public void restorecont()
{
restorecont(this);
}
// Restore continuation
public void restorecont(Callable caller)
{
if (cont instanceof Fixnum) {
sp = (int)((Fixnum)cont).fixnum;
cont = pop();
setenvreg(pop());
setBP((int)((Fixnum)pop()).fixnum);
setIP((int)((Fixnum)pop()).fixnum);
} else if (cont instanceof Continuation) {
Continuation ct = (Continuation)cont;
ct.restore(this, caller);
} else if (cont.is(Nil.NIL)) {
// If we have no continuation, that was an attempt to return from the topmost
// level and we should halt the machine.
halt();
} else {
throw new NekoArcException("invalid continuation");
}
}
public void setenvreg(ArcObject env)
{
this.env = env;
}
public int getBP()
{
return bp;
}
public void setBP(int bp)
{
this.bp = bp;
}
public ArcObject getCont()
{
return cont;
}
public void setCont(ArcObject cont)
{
this.cont = cont;
}
@Override
public CallSync sync()
{
return(caller);
}
}
|
dido/arcueid
|
39719e6241d2631af3fed8d86965ea81fbc497d1
|
magic stack size that results in stack overflow on continuations
|
diff --git a/java/test/org/arcueidarc/nekoarc/vm/FibonacciTest.java b/java/test/org/arcueidarc/nekoarc/vm/FibonacciTest.java
index fb73e7d..049c3ee 100644
--- a/java/test/org/arcueidarc/nekoarc/vm/FibonacciTest.java
+++ b/java/test/org/arcueidarc/nekoarc/vm/FibonacciTest.java
@@ -1,72 +1,72 @@
package org.arcueidarc.nekoarc.vm;
import static org.junit.Assert.*;
import org.arcueidarc.nekoarc.types.ArcObject;
import org.arcueidarc.nekoarc.types.Fixnum;
import org.arcueidarc.nekoarc.types.Closure;
import org.arcueidarc.nekoarc.Nil;
import org.junit.Test;
public class FibonacciTest
{
/* This is a recursive Fibonacci test, essentially (afn (x) (if (is x 0) 1 (is x 1) 1 (+ (self (- x 1)) (self (- x 2)))))
* Since this isn't tail recursive it runs in exponential time and will use up a lot of stack space for continuations.
* If we don't migrate continuations to the heap this will very quickly use up stack space if it's set low enough.
*/
@Test
public void test()
{
// env 1 0 0; lde0 0; push; ldi 0; is; jf xxx; ldi 1; ret; lde0 0; push ldi 1; is; jf xxx; ldi 1; ret;
// cont xxx; lde0 0; push; ldi 1; sub; push; ldl 0; apply 1; push;
// cont xxx; lde0 0; push; ldi 2; sub; push; ldl 0; apply 1; add; ret
byte inst[] = { (byte)0xca, 0x01, 0x00, 0x00, // env 1 0 0
0x69, 0x00, // lde0 0
0x01, // push
0x44, 0x00, 0x00, 0x00, 0x00, // ldi 0
0x1f, // is
0x50, 0x06, 0x00, 0x00, 0x00, // jf L1 (6)
0x44, 0x01, 0x00, 0x00, 0x00, // ldi 1
0x0d, // ret
0x69, 0x00, // L1: lde0 0
0x01, // push
0x44, 0x01, 0x00, 0x00, 0x00, // ldi 1
0x1f, // is
0x50, 0x06, 0x00, 0x00, 0x00, // jf L2 (6)
0x44, 0x01, 0x00, 0x00, 0x00, // ldi 1
0x0d, // ret
(byte)0x89, 0x11, 0x00, 0x00, 0x00, // L2: cont L3 (0x11)
0x69, 0x00, // lde0 0
0x01, // push
0x44, 0x01, 0x00, 0x00, 0x00, // ldi 1
0x16, // sub
0x01, // push
0x43, 0x00, 0x00, 0x00, 0x00, // ldl 0
0x4c, 0x01, // apply 1
0x01, // L3: push
(byte)0x89, 0x11, 0x00, 0x00, 0x00, // cont L4 (0x11)
0x69, 0x00, // lde0 0
0x01, // push
0x44, 0x02, 0x00, 0x00, 0x00, // ldi 2
0x16, // sub
0x01, // push
0x43, 0x00, 0x00, 0x00, 0x00, // ldl 0
0x4c, 0x01, // apply 1
0x15, // add
0x0d // ret
};
- VirtualMachine vm = new VirtualMachine(12);
+ VirtualMachine vm = new VirtualMachine(8);
ArcObject literals[] = new ArcObject[1];
literals[0] = new Closure(Nil.NIL, Fixnum.get(0));
vm.load(inst, 0, literals);
vm.setargc(1);
vm.push(Fixnum.get(25));
vm.setAcc(Nil.NIL);
assertTrue(vm.runnable());
vm.run();
assertFalse(vm.runnable());
assertEquals(121393, ((Fixnum)vm.getAcc()).fixnum);
}
}
|
dido/arcueid
|
3a2acf15b05e8ebd0278f34c2d7c1062b535acb9
|
cases to verify stack gc usage
|
diff --git a/java/test/org/arcueidarc/nekoarc/vm/HeapContinuationTest.java b/java/test/org/arcueidarc/nekoarc/vm/HeapContinuationTest.java
index 4d74daa..aa7cb7a 100644
--- a/java/test/org/arcueidarc/nekoarc/vm/HeapContinuationTest.java
+++ b/java/test/org/arcueidarc/nekoarc/vm/HeapContinuationTest.java
@@ -1,168 +1,168 @@
package org.arcueidarc.nekoarc.vm;
import static org.junit.Assert.*;
import org.arcueidarc.nekoarc.HeapContinuation;
import org.arcueidarc.nekoarc.HeapEnv;
import org.arcueidarc.nekoarc.Nil;
import org.arcueidarc.nekoarc.types.ArcObject;
import org.arcueidarc.nekoarc.types.Closure;
import org.arcueidarc.nekoarc.types.Fixnum;
import org.junit.Test;
public class HeapContinuationTest
{
/** First we try to invent a HeapContinuation out of whole cloth. */
@Test
public void test()
{
HeapContinuation hc;
// Prepare an environment
HeapEnv env = new HeapEnv(3, Nil.NIL);
env.setEnv(0, Fixnum.get(4));
env.setEnv(1, Fixnum.get(5));
env.setEnv(2, Fixnum.get(6));
// Synthetic HeapContinuation
hc = new HeapContinuation(3, // 3 stack elements
Nil.NIL, // previous continuation
env, // environment
20); // saved IP
// Stack elements
hc.setIndex(0, Fixnum.get(1));
hc.setIndex(1, Fixnum.get(2));
hc.setIndex(2, Fixnum.get(3));
// Code:
// env 2 0 0; lde0 0; push; lde0 1; apply 1; ret; hlt; hlt; hlt; hlt; hlt;
// add everything already on the stack to the value applied to the continuation, get the
// stuff in the environment and add it too, and return the sum.
// add; add; add; push; lde0 0; add; push; lde0 1; add; push; lde0 2; add; ret
byte inst[] = { (byte)0xca, 0x02, 0x00, 0x00, // env 1 0 0
0x69, 0x00, // lde0 0 ; value (fixnum)
0x01, // push
0x69, 0x01, // lde0 1 ; continuation
0x4c, 0x01, // apply 1
0x0d, // ret
0x14, // hlt
0x14, // hlt
0x14, // hlt
0x14, // hlt
0x14, // hlt
0x14, // hlt
0x14, // hlt
0x14, // hlt
0x15, // add ; continuation ip address
0x15, // add
0x15, // add
0x01, // push
0x69, 0x00, // lde0 0
0x15, // add
0x01, // push
0x69, 0x01, // lde0 1
0x15, // add
0x01, // push
0x69, 0x02, // lde0 2
0x15, // add
0x0d, // ret
};
VirtualMachine vm = new VirtualMachine(1024);
vm.load(inst, 0);
vm.setargc(2);
vm.push(Fixnum.get(7));
vm.push(hc);
vm.setAcc(Nil.NIL);
assertTrue(vm.runnable());
vm.run();
assertFalse(vm.runnable());
assertEquals(28, ((Fixnum)vm.getAcc()).fixnum);
}
/** Next, we make a function that recurses several times, essentially
* (afn (x) (if (is x 0) 0 (+ (self (- x 1)) 2)))
* If stack space is very limited on the VM, the continuations that the recursive calls need to make should
* eventually migrate from the stack to the heap.
*/
@Test
public void test2()
{
// env 1 0 0; lde0 0; push; ldi 0; is; jf L1; ldi 2; ret;
- // L1: cont L2; lde0 0; push; ldi 1; sub; push; ldl 0; apply 1; L2: push; add; ret
+ // L1: cont L2; lde0 0; push; ldi 1; sub; push; ldl 0; apply 1; L2: push; ldi 2; add; ret
byte inst[] = { (byte)0xca, 0x01, 0x00, 0x00, // env 1 0 0
0x69, 0x00, // lde0 0
0x01, // push
0x44, 0x00, 0x00, 0x00, 0x00, // ldi 0
0x1f, // is
0x50, 0x06, 0x00, 0x00, 0x00, // jf L1 (6)
0x44, 0x00, 0x00, 0x00, 0x00, // ldi 0
0x0d, // ret
(byte)0x89, 0x11, 0x00, 0x00, 0x00, // L1: cont L2 (0x11)
0x69, 0x00, // lde0 0
0x01, // push
0x44, 0x01, 0x00, 0x00, 0x00, // ldi 1
0x16, // sub
0x01, // push
0x43, 0x00, 0x00, 0x00, 0x00, // ldl 0
0x4c, 0x01, // apply 1
0x01, // L2: push
0x44, 0x02, 0x00, 0x00, 0x00, // ldi 2
0x15, // add
0x0d // ret
};
VirtualMachine vm = new VirtualMachine(4);
ArcObject literals[] = new ArcObject[1];
literals[0] = new Closure(Nil.NIL, Fixnum.get(0));
vm.load(inst, 0, literals);
vm.setargc(1);
vm.push(Fixnum.get(100));
vm.setAcc(literals[0]);
assertTrue(vm.runnable());
vm.run();
assertFalse(vm.runnable());
assertEquals(200, ((Fixnum)vm.getAcc()).fixnum);
}
/** Next, we make a slight variation
* (afn (x) (if (is x 0) 0 (+ 2 (self (- x 1)))))
*/
@Test
public void test3()
{
// env 1 0 0; lde0 0; push; ldi 0; is; jf L1; ldi 2; ret;
- // L1: cont L2; lde0 0; push; ldi 1; sub; push; ldl 0; apply 1; L2: push; add; ret
+ // L1: ldi 2; push; cont L2; lde0 0; push; ldi 1; sub; push; ldl 0; apply 1; L2: add; ret
byte inst[] = { (byte)0xca, 0x01, 0x00, 0x00, // env 1 0 0
0x69, 0x00, // lde0 0
0x01, // push
0x44, 0x00, 0x00, 0x00, 0x00, // ldi 0
0x1f, // is
0x50, 0x06, 0x00, 0x00, 0x00, // jf L1 (6)
0x44, 0x00, 0x00, 0x00, 0x00, // ldi 0
0x0d, // ret
- (byte)0x89, 0x17, 0x00, 0x00, 0x00, // L1: cont L2 (0x17)
- 0x44, 0x02, 0x00, 0x00, 0x00, // ldi 2
+ 0x44, 0x02, 0x00, 0x00, 0x00, // L1: ldi 2
0x01, // push
+ (byte)0x89, 0x11, 0x00, 0x00, 0x00, // cont L2 (0x11)
0x69, 0x00, // lde0 0
0x01, // push
0x44, 0x01, 0x00, 0x00, 0x00, // ldi 1
0x16, // sub
0x01, // push
0x43, 0x00, 0x00, 0x00, 0x00, // ldl 0
0x4c, 0x01, // apply 1
0x15, // L2: add
0x0d // ret
};
- VirtualMachine vm = new VirtualMachine(6);
+ VirtualMachine vm = new VirtualMachine(5);
ArcObject literals[] = new ArcObject[1];
literals[0] = new Closure(Nil.NIL, Fixnum.get(0));
vm.load(inst, 0, literals);
vm.setargc(1);
- vm.push(Fixnum.get(100));
+ vm.push(Fixnum.get(1));
vm.setAcc(literals[0]);
assertTrue(vm.runnable());
vm.run();
assertFalse(vm.runnable());
- assertEquals(200, ((Fixnum)vm.getAcc()).fixnum);
+ assertEquals(2, ((Fixnum)vm.getAcc()).fixnum);
}
}
|
dido/arcueid
|
feb76d61ddb9c53bf7785ffbb59c2f31e916cc3b
|
more bugfixes in stack gc
|
diff --git a/java/src/org/arcueidarc/nekoarc/vm/VirtualMachine.java b/java/src/org/arcueidarc/nekoarc/vm/VirtualMachine.java
index 064c852..282055e 100644
--- a/java/src/org/arcueidarc/nekoarc/vm/VirtualMachine.java
+++ b/java/src/org/arcueidarc/nekoarc/vm/VirtualMachine.java
@@ -1,673 +1,675 @@
package org.arcueidarc.nekoarc.vm;
import org.arcueidarc.nekoarc.Continuation;
import org.arcueidarc.nekoarc.HeapContinuation;
import org.arcueidarc.nekoarc.HeapEnv;
import org.arcueidarc.nekoarc.NekoArcException;
import org.arcueidarc.nekoarc.Nil;
import org.arcueidarc.nekoarc.Unbound;
import org.arcueidarc.nekoarc.types.ArcObject;
import org.arcueidarc.nekoarc.types.Fixnum;
import org.arcueidarc.nekoarc.types.Symbol;
import org.arcueidarc.nekoarc.util.CallSync;
import org.arcueidarc.nekoarc.util.Callable;
import org.arcueidarc.nekoarc.util.ObjectMap;
import org.arcueidarc.nekoarc.vm.instruction.*;
public class VirtualMachine implements Callable
{
private int sp; // stack pointer
private int bp; // base pointer
private ArcObject env; // environment pointer
private ArcObject cont; // continuation pointer
private ArcObject[] stack; // stack
private final CallSync caller;
private int ip; // instruction pointer
private byte[] code;
private boolean runnable;
private ArcObject acc; // accumulator
private ArcObject[] literals;
private int argc; // argument counter for current function
private static final INVALID NOINST = new INVALID();
private static final Instruction[] jmptbl = {
new NOP(), // 0x00
new PUSH(), // 0x01
new POP(), // 0x02
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
new RET(), // 0x0d
NOINST,
NOINST,
NOINST,
new NO(), // 0x11
new TRUE(), // 0x12
new NIL(), // 0x13
new HLT(), // 0x14
new ADD(), // 0x15
new SUB(), // 0x16
new MUL(), // 0x17
new DIV(), // 0x18
new CONS(), // 0x19
new CAR(), // 0x1a
new CDR(), // 0x1b
new SCAR(), // 0x1c
new SCDR(), // 0x1d
NOINST,
new IS(), // 0x1f
NOINST,
NOINST,
new DUP(), // 0x22
NOINST, // 0x23
new CONSR(), // 0x24
NOINST,
new DCAR(), // 0x26
new DCDR(), // 0x27
new SPL(), // 0x28
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
new LDL(), // 0x43
new LDI(), // 0x44
new LDG(), // 0x45
new STG(), // 0x46
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
new APPLY(), // 0x4c
new CLS(), // 0x4d,
new JMP(), // 0x4e
new JT(), // 0x4f
new JF(), // 0x50
new JBND(), // 0x51
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
new MENV(), // 0x65
NOINST,
NOINST,
NOINST,
new LDE0(), // 0x69
new STE0(), // 0x6a
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
new LDE(), // 0x87
new STE(), // 0x88
new CONT(), // 0x89
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
new ENV(), // 0xca
new ENVR(), // 0xcb
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
};
private ObjectMap<Symbol, ArcObject> genv = new ObjectMap<Symbol, ArcObject>();
public VirtualMachine(int stacksize)
{
sp = bp = 0;
stack = new ArcObject[stacksize];
ip = 0;
code = null;
runnable = true;
env = Nil.NIL;
cont = Nil.NIL;
setAcc(Nil.NIL);
caller = new CallSync();
}
public void load(final byte[] instructions, int ip, final ArcObject[] literals)
{
this.code = instructions;
this.literals = literals;
this.ip = ip;
}
public void load(final byte[] instructions, int ip)
{
load(instructions, ip, null);
}
public void halt()
{
runnable = false;
}
public void nextI()
{
ip++;
}
/**
* Attempt to garbage collect the stack, after Richard A. Kelsey, "Tail Recursive Stack Disciplines for an Interpreter"
* Basically, the only things on the stack that are garbage collected are environments and continuations.
* The algorithm here works by copying all environments and continuations from the stack to the heap. When that's done it will move the stack pointer
* to the top of the stack.
* 1. Start with the environment register. Move that environment and all of its children to the heap.
* 2. Continue with the continuation register. Copy the current continuation into the heap.
* 3. Compact the stack by moving the remainder of the non-stack/non-continuation elements to the heap.
*/
private void stackgc()
{
int[] deepest = {sp};
if (env instanceof Fixnum)
env = HeapEnv.fromStackEnv(this, env, deepest);
// If the current continuation is on the stack move it to the heap
if (cont instanceof Fixnum)
this.setCont(HeapContinuation.fromStackCont(this, cont, deepest));
int stackbottom = deepest[0];
// Garbage collection failed to produce memory
- if (stackbottom < 0 || stackbottom > stack.length || stackbottom == bp)
+ if (stackbottom < 0 || stackbottom > stack.length || stackbottom == sp)
return;
// move what we can of the used portion of the stack to the lowest part of the stack we can reach.
- for (int i=0; i<sp - bp - 1; i++)
+ for (int i=0; i<sp - bp; i++)
setStackIndex(stackbottom + i, stackIndex(bp + i));
- sp = stackbottom + (sp - bp - 1);
+ sp = stackbottom + (sp - bp);
bp = stackbottom;
}
public void push(ArcObject obj)
{
for (;;) {
try {
stack[sp++] = obj;
return;
} catch (ArrayIndexOutOfBoundsException e) {
- // We can try to garbage collect the stack
+ // Restore sp to its old value before stack gc
+ sp--;
stackgc();
if (sp >= stack.length)
throw new NekoArcException("stack overflow");
}
}
}
public ArcObject pop()
{
return(stack[--sp]);
}
public void run()
throws NekoArcException
{
while (runnable) {
jmptbl[(int)code[ip++] & 0xff].invoke(this);
}
}
// Four-byte instruction arguments (most everything else). Little endian.
public int instArg()
{
long val = 0;
int data;
for (int i=0; i<4; i++) {
data = (((int)code[ip++]) & 0xff);
val |= data << i*8;
}
return((int)((val << 1) >> 1));
}
// one-byte instruction arguments (LDE/STE/ENV, etc.)
public byte smallInstArg()
{
return(code[ip++]);
}
public ArcObject getAcc()
{
return acc;
}
public void setAcc(ArcObject acc)
{
this.acc = acc;
}
public boolean runnable()
{
return(this.runnable);
}
public boolean setrunnable(boolean runstate)
{
this.runnable = runstate;
return(runstate);
}
public ArcObject literal(int offset)
{
return(literals[offset]);
}
public int getIP()
{
return ip;
}
public void setIP(int ip)
{
this.ip = ip;
}
public int getSP()
{
return(sp);
}
public void setSP(int sp)
{
this.sp = sp;
}
// add or replace a global binding
public ArcObject bind(Symbol sym, ArcObject binding)
{
genv.put(sym, binding);
return(binding);
}
public ArcObject value(Symbol sym)
{
if (!genv.containsKey(sym))
throw new NekoArcException("Unbound symbol " + sym);
return(genv.get(sym));
}
public int argc()
{
return(argc);
}
public int setargc(int ac)
{
return(argc = ac);
}
public void argcheck(int minarg, int maxarg)
{
if (argc() < minarg)
throw new NekoArcException("too few arguments, at least " + minarg + " required, " + argc() + " passed");
if (maxarg >= 0 && argc() > maxarg)
throw new NekoArcException("too many arguments, at most " + maxarg + " allowed, " + argc() + " passed");
}
public void argcheck(int arg)
{
argcheck(arg, arg);
}
/* Create an environment. If there is enough space on the stack, that environment will be there,
* if not, it will be created in the heap. */
public void mkenv(int prevsize, int extrasize)
{
if (sp + extrasize + 3 > stack.length) {
mkheapenv(prevsize, extrasize);
return;
}
// If there is enough space on the stack, create the environment there.
// Add the extra environment entries
for (int i=0; i<extrasize; i++)
push(Unbound.UNBOUND);
int count = prevsize + extrasize;
int envstart = sp - count;
/* Stack environments are basically Fixnum pointers into the stack. */
int envptr = sp;
push(Fixnum.get(envstart)); // envptr
push(Fixnum.get(count)); // envptr + 1
push(env); // envptr + 2
env = Fixnum.get(envptr);
bp = sp;
}
/** Create a new heap environment ab initio */
private void mkheapenv(int prevsize, int extrasize)
{
// First, convert what will become the parent environment to a heap environment if it is not already one
env = HeapEnv.fromStackEnv(this, env);
int envstart = sp - prevsize;
// Create new heap environment and copy the environment values from the stack into it
HeapEnv nenv = new HeapEnv(prevsize + extrasize, env);
for (int i=0; i<prevsize; i++)
nenv.setEnv(i, stackIndex(envstart + i));
// Fill in extra environment entries with UNBOUND
for (int i=prevsize; i<prevsize+extrasize; i++)
nenv.setEnv(i, Unbound.UNBOUND);
bp = sp;
env = nenv;
}
/** move current environment to heap if needed */
public ArcObject heapenv()
{
env = HeapEnv.fromStackEnv(this, env);
return(env);
}
private ArcObject findenv(int depth)
{
ArcObject cenv = env;
while (depth-- > 0 && !cenv.is(Nil.NIL)) {
if (cenv instanceof Fixnum) {
int index = (int)((Fixnum)cenv).fixnum;
cenv = stackIndex(index+2);
} else {
HeapEnv e = (HeapEnv)cenv;
cenv = e.prevEnv();
}
}
return(cenv);
}
public ArcObject getenv(int depth, int index)
{
ArcObject cenv = findenv(depth);
if (cenv == Nil.NIL)
throw new NekoArcException("environment depth exceeded");
if (cenv instanceof Fixnum) {
int si = (int)((Fixnum)cenv).fixnum;
int start = (int)((Fixnum)stackIndex(si)).fixnum;
int size = (int)((Fixnum)stackIndex(si+1)).fixnum;
if (index > size)
throw new NekoArcException("stack environment index exceeded");
return(stackIndex(start+index));
}
return(((HeapEnv)cenv).getEnv(index));
}
public ArcObject setenv(int depth, int index, ArcObject value)
{
ArcObject cenv = findenv(depth);
if (cenv == Nil.NIL)
throw new NekoArcException("environment depth exceeded");
if (cenv instanceof Fixnum) {
int si = (int)((Fixnum)cenv).fixnum;
int start = (int)((Fixnum)stackIndex(si)).fixnum;
int size = (int)((Fixnum)stackIndex(si+1)).fixnum;
if (index > size)
throw new NekoArcException("stack environment index exceeded");
return(setStackIndex(start+index, value));
}
return(((HeapEnv)cenv).setEnv(index,value));
}
public ArcObject stackIndex(int index)
{
return(stack[index]);
}
public ArcObject setStackIndex(int index, ArcObject value)
{
return(stack[index] = value);
}
public void stackcheck(int required, final String message)
{
if (sp + required > stack.length) {
// Try to do stack gc first. If it fails, nothing for it
stackgc();
if (sp + required > stack.length)
throw new NekoArcException(message);
}
}
+
// Make a continuation on the stack. The new continuation is saved in the continuation register.
public void makecont(int ipoffset)
{
stackcheck(4, "stack overflow while creating continuation");
int newip = ip + ipoffset;
push(Fixnum.get(newip));
push(Fixnum.get(bp));
push(env);
push(cont);
cont = Fixnum.get(sp);
bp = sp;
}
public void restorecont()
{
restorecont(this);
}
// Restore continuation
public void restorecont(Callable caller)
{
if (cont instanceof Fixnum) {
sp = (int)((Fixnum)cont).fixnum;
cont = pop();
setenvreg(pop());
setBP((int)((Fixnum)pop()).fixnum);
setIP((int)((Fixnum)pop()).fixnum);
} else if (cont instanceof Continuation) {
Continuation ct = (Continuation)cont;
ct.restore(this, caller);
} else if (cont.is(Nil.NIL)) {
// If we have no continuation, that was an attempt to return from the topmost
// level and we should halt the machine.
halt();
} else {
throw new NekoArcException("invalid continuation");
}
}
public void setenvreg(ArcObject env)
{
this.env = env;
}
public int getBP()
{
return bp;
}
public void setBP(int bp)
{
this.bp = bp;
}
public ArcObject getCont()
{
return cont;
}
public void setCont(ArcObject cont)
{
this.cont = cont;
}
@Override
public CallSync sync()
{
return(caller);
}
}
|
dido/arcueid
|
a0c8aeb392a5af8682f027102be943e07f6a0034
|
calculate deepest stack reached if optional parameter specified
|
diff --git a/java/src/org/arcueidarc/nekoarc/HeapContinuation.java b/java/src/org/arcueidarc/nekoarc/HeapContinuation.java
index 6806552..de9990d 100644
--- a/java/src/org/arcueidarc/nekoarc/HeapContinuation.java
+++ b/java/src/org/arcueidarc/nekoarc/HeapContinuation.java
@@ -1,99 +1,101 @@
package org.arcueidarc.nekoarc;
import org.arcueidarc.nekoarc.types.ArcObject;
import org.arcueidarc.nekoarc.types.Fixnum;
import org.arcueidarc.nekoarc.types.Symbol;
import org.arcueidarc.nekoarc.types.Vector;
import org.arcueidarc.nekoarc.util.Callable;
import org.arcueidarc.nekoarc.vm.VirtualMachine;
public class HeapContinuation extends Vector implements Continuation
{
public static final ArcObject TYPE = Symbol.intern("continuation");
private final ArcObject prevcont;
private final ArcObject env;
private final int ipoffset;
public HeapContinuation(int size, ArcObject pcont, ArcObject e, int ip)
{
super(size);
prevcont = pcont;
env = e;
ipoffset = ip;
}
@Override
/**
* Move heap continuation to stack for restoration.
*/
public void restore(VirtualMachine vm, Callable cc)
{
int svsize = this.length();
vm.stackcheck(svsize + 4, "stack overflow while restoring heap continuation");
int bp = vm.getSP();
// push the saved stack values back to the stack
for (int i=0; i<svsize; i++)
vm.push(index(i));
// push the saved instruction pointer
vm.push(Fixnum.get(ipoffset));
// push the new base pointer
vm.push(Fixnum.get(bp));
// push the saved environment
vm.push(env);
// push the previous continuation
vm.push(prevcont);
vm.setCont(Fixnum.get(vm.getSP()));
+ vm.restorecont();
}
public static ArcObject fromStackCont(VirtualMachine vm, ArcObject sc)
{
return(fromStackCont(vm, sc, null));
}
/**
* Create a new heap continuation from a stack-based continuation.
* A stack continuation is a pointer into the stack, such that
* [cont-1] -> previous continuation
* [cont-2] -> environment
* [cont-3] -> base pointer
* [cont-4] -> instruction pointer offset
* [cont-(5+n)] -> saved stack elements up to saved base pointer position
* This function copies all of this relevant information to the a new HeapContinuation so it can later be restored
*/
public static ArcObject fromStackCont(VirtualMachine vm, ArcObject sc, int[] deepest)
{
if (sc instanceof HeapContinuation || sc.is(Nil.NIL))
return(sc);
int cc = (int)((Fixnum)sc).fixnum;
// Calculate the size of the actual continuation based on the saved base pointer
int bp = (int)((Fixnum)vm.stackIndex(cc-3)).fixnum;
int svsize = cc - bp - 4;
- if (deepest != null)
+ if (deepest != null && deepest[0] > bp)
deepest[0] = bp;
// Turn previous continuation into a heap-based one too
ArcObject pco = vm.stackIndex(cc-1);
pco = fromStackCont(vm, pco, deepest);
- HeapContinuation c = new HeapContinuation(svsize, pco, HeapEnv.fromStackEnv(vm, vm.stackIndex(cc-2)), (int)((Fixnum)vm.stackIndex(cc-4)).fixnum);
+ ArcObject senv = HeapEnv.fromStackEnv(vm, vm.stackIndex(cc-2), deepest);
+ HeapContinuation c = new HeapContinuation(svsize, pco, senv, (int)((Fixnum)vm.stackIndex(cc-4)).fixnum);
for (int i=0; i<svsize; i++)
c.setIndex(i, vm.stackIndex(bp + i));
return(c);
}
@Override
public int requiredArgs()
{
return(1);
}
/** The application of a continuation -- this will set itself as the current continuation,
* ready to be restored just as the invokethread terminates. */
@Override
public ArcObject invoke(InvokeThread thr)
{
thr.vm.setCont(this);
return(thr.getenv(0, 0));
}
}
diff --git a/java/src/org/arcueidarc/nekoarc/HeapEnv.java b/java/src/org/arcueidarc/nekoarc/HeapEnv.java
index 706a424..2202aa3 100644
--- a/java/src/org/arcueidarc/nekoarc/HeapEnv.java
+++ b/java/src/org/arcueidarc/nekoarc/HeapEnv.java
@@ -1,54 +1,61 @@
package org.arcueidarc.nekoarc;
import org.arcueidarc.nekoarc.types.ArcObject;
import org.arcueidarc.nekoarc.types.Fixnum;
import org.arcueidarc.nekoarc.types.Symbol;
import org.arcueidarc.nekoarc.types.Vector;
import org.arcueidarc.nekoarc.vm.VirtualMachine;
/** Heap environment */
public class HeapEnv extends Vector
{
public static final ArcObject TYPE = Symbol.intern("environment");
private ArcObject prev;
public HeapEnv(int size, ArcObject p)
{
super(size);
prev = p;
}
public ArcObject prevEnv()
{
return(prev);
}
public ArcObject getEnv(int index) throws NekoArcException
{
return(this.index(index));
}
public ArcObject setEnv(int index, ArcObject value)
{
return(setIndex(index, value));
}
+ public static ArcObject fromStackEnv(VirtualMachine vm, ArcObject sei)
+ {
+ return(fromStackEnv(vm, sei, null));
+ }
+
// Convert a stack-based environment si into a heap environment. Also affects any
// environments linked to it.
- public static ArcObject fromStackEnv(VirtualMachine vm, ArcObject sei)
+ public static ArcObject fromStackEnv(VirtualMachine vm, ArcObject sei, int[] deepest)
{
if (sei instanceof HeapEnv || sei.is(Nil.NIL))
return(sei);
int si = (int)((Fixnum)sei).fixnum;
int start = (int)((Fixnum)vm.stackIndex(si)).fixnum;
int size = (int)((Fixnum)vm.stackIndex(si+1)).fixnum;
ArcObject penv = vm.stackIndex(si+2);
+ if (deepest != null && deepest[0] > start)
+ deepest[0] = start;
// Convert previous env into a stack-based one too
penv = fromStackEnv(vm, penv);
HeapEnv nenv = new HeapEnv(size, penv);
// Copy stack env data to new env
for (int i=0; i<size; i++)
nenv.setEnv(i, vm.stackIndex(start + i));
return(nenv);
}
}
|
dido/arcueid
|
394a17e2391a243559178db0c7e48f7ada3b797e
|
cleanup of stack gc and continuation restoration
|
diff --git a/java/src/org/arcueidarc/nekoarc/vm/VirtualMachine.java b/java/src/org/arcueidarc/nekoarc/vm/VirtualMachine.java
index 8f8d300..064c852 100644
--- a/java/src/org/arcueidarc/nekoarc/vm/VirtualMachine.java
+++ b/java/src/org/arcueidarc/nekoarc/vm/VirtualMachine.java
@@ -1,684 +1,673 @@
package org.arcueidarc.nekoarc.vm;
import org.arcueidarc.nekoarc.Continuation;
import org.arcueidarc.nekoarc.HeapContinuation;
import org.arcueidarc.nekoarc.HeapEnv;
import org.arcueidarc.nekoarc.NekoArcException;
import org.arcueidarc.nekoarc.Nil;
import org.arcueidarc.nekoarc.Unbound;
import org.arcueidarc.nekoarc.types.ArcObject;
import org.arcueidarc.nekoarc.types.Fixnum;
import org.arcueidarc.nekoarc.types.Symbol;
import org.arcueidarc.nekoarc.util.CallSync;
import org.arcueidarc.nekoarc.util.Callable;
import org.arcueidarc.nekoarc.util.ObjectMap;
import org.arcueidarc.nekoarc.vm.instruction.*;
public class VirtualMachine implements Callable
{
private int sp; // stack pointer
private int bp; // base pointer
private ArcObject env; // environment pointer
private ArcObject cont; // continuation pointer
private ArcObject[] stack; // stack
private final CallSync caller;
private int ip; // instruction pointer
private byte[] code;
private boolean runnable;
private ArcObject acc; // accumulator
private ArcObject[] literals;
private int argc; // argument counter for current function
private static final INVALID NOINST = new INVALID();
private static final Instruction[] jmptbl = {
new NOP(), // 0x00
new PUSH(), // 0x01
new POP(), // 0x02
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
new RET(), // 0x0d
NOINST,
NOINST,
NOINST,
new NO(), // 0x11
new TRUE(), // 0x12
new NIL(), // 0x13
new HLT(), // 0x14
new ADD(), // 0x15
new SUB(), // 0x16
new MUL(), // 0x17
new DIV(), // 0x18
new CONS(), // 0x19
new CAR(), // 0x1a
new CDR(), // 0x1b
new SCAR(), // 0x1c
new SCDR(), // 0x1d
NOINST,
new IS(), // 0x1f
NOINST,
NOINST,
new DUP(), // 0x22
NOINST, // 0x23
new CONSR(), // 0x24
NOINST,
new DCAR(), // 0x26
new DCDR(), // 0x27
new SPL(), // 0x28
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
new LDL(), // 0x43
new LDI(), // 0x44
new LDG(), // 0x45
new STG(), // 0x46
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
new APPLY(), // 0x4c
new CLS(), // 0x4d,
new JMP(), // 0x4e
new JT(), // 0x4f
new JF(), // 0x50
new JBND(), // 0x51
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
new MENV(), // 0x65
NOINST,
NOINST,
NOINST,
new LDE0(), // 0x69
new STE0(), // 0x6a
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
new LDE(), // 0x87
new STE(), // 0x88
new CONT(), // 0x89
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
new ENV(), // 0xca
new ENVR(), // 0xcb
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
};
private ObjectMap<Symbol, ArcObject> genv = new ObjectMap<Symbol, ArcObject>();
public VirtualMachine(int stacksize)
{
sp = bp = 0;
stack = new ArcObject[stacksize];
ip = 0;
code = null;
runnable = true;
env = Nil.NIL;
cont = Nil.NIL;
setAcc(Nil.NIL);
caller = new CallSync();
}
public void load(final byte[] instructions, int ip, final ArcObject[] literals)
{
this.code = instructions;
this.literals = literals;
this.ip = ip;
}
public void load(final byte[] instructions, int ip)
{
load(instructions, ip, null);
}
public void halt()
{
runnable = false;
}
public void nextI()
{
ip++;
}
/**
* Attempt to garbage collect the stack, after Richard A. Kelsey, "Tail Recursive Stack Disciplines for an Interpreter"
* Basically, the only things on the stack that are garbage collected are environments and continuations.
* The algorithm here works by copying all environments and continuations from the stack to the heap. When that's done it will move the stack pointer
* to the top of the stack.
* 1. Start with the environment register. Move that environment and all of its children to the heap.
* 2. Continue with the continuation register. Copy the current continuation into the heap.
* 3. Compact the stack by moving the remainder of the non-stack/non-continuation elements to the heap.
*/
private void stackgc()
{
- int stackbottom = -1;
+ int[] deepest = {sp};
- if (env instanceof Fixnum) {
- int si = (int)((Fixnum)env).fixnum;
- stackbottom = (int)((Fixnum)stackIndex(si)).fixnum;
- env = HeapEnv.fromStackEnv(this, env);
- }
+ if (env instanceof Fixnum)
+ env = HeapEnv.fromStackEnv(this, env, deepest);
- if (cont instanceof Fixnum) {
- int[] deepest = {0};
- // If the current continuation is on the stack move it to the heap
- ArcObject nc = HeapContinuation.fromStackCont(this, cont, deepest);
- this.setCont(nc);
- stackbottom = deepest[0];
-// stackbottom = (int)((Fixnum)cont).fixnum + 1;
- }
+ // If the current continuation is on the stack move it to the heap
+ if (cont instanceof Fixnum)
+ this.setCont(HeapContinuation.fromStackCont(this, cont, deepest));
+ int stackbottom = deepest[0];
// Garbage collection failed to produce memory
if (stackbottom < 0 || stackbottom > stack.length || stackbottom == bp)
return;
- // move what we can of the used portion of the stack to the bottom.
+ // move what we can of the used portion of the stack to the lowest part of the stack we can reach.
for (int i=0; i<sp - bp - 1; i++)
setStackIndex(stackbottom + i, stackIndex(bp + i));
sp = stackbottom + (sp - bp - 1);
bp = stackbottom;
}
public void push(ArcObject obj)
{
for (;;) {
try {
stack[sp++] = obj;
return;
} catch (ArrayIndexOutOfBoundsException e) {
// We can try to garbage collect the stack
stackgc();
if (sp >= stack.length)
throw new NekoArcException("stack overflow");
}
}
}
public ArcObject pop()
{
return(stack[--sp]);
}
public void run()
throws NekoArcException
{
while (runnable) {
jmptbl[(int)code[ip++] & 0xff].invoke(this);
}
}
// Four-byte instruction arguments (most everything else). Little endian.
public int instArg()
{
long val = 0;
int data;
for (int i=0; i<4; i++) {
data = (((int)code[ip++]) & 0xff);
val |= data << i*8;
}
return((int)((val << 1) >> 1));
}
// one-byte instruction arguments (LDE/STE/ENV, etc.)
public byte smallInstArg()
{
return(code[ip++]);
}
public ArcObject getAcc()
{
return acc;
}
public void setAcc(ArcObject acc)
{
this.acc = acc;
}
public boolean runnable()
{
return(this.runnable);
}
public boolean setrunnable(boolean runstate)
{
this.runnable = runstate;
return(runstate);
}
public ArcObject literal(int offset)
{
return(literals[offset]);
}
public int getIP()
{
return ip;
}
public void setIP(int ip)
{
this.ip = ip;
}
public int getSP()
{
return(sp);
}
public void setSP(int sp)
{
this.sp = sp;
}
// add or replace a global binding
public ArcObject bind(Symbol sym, ArcObject binding)
{
genv.put(sym, binding);
return(binding);
}
public ArcObject value(Symbol sym)
{
if (!genv.containsKey(sym))
throw new NekoArcException("Unbound symbol " + sym);
return(genv.get(sym));
}
public int argc()
{
return(argc);
}
public int setargc(int ac)
{
return(argc = ac);
}
public void argcheck(int minarg, int maxarg)
{
if (argc() < minarg)
throw new NekoArcException("too few arguments, at least " + minarg + " required, " + argc() + " passed");
if (maxarg >= 0 && argc() > maxarg)
throw new NekoArcException("too many arguments, at most " + maxarg + " allowed, " + argc() + " passed");
}
public void argcheck(int arg)
{
argcheck(arg, arg);
}
/* Create an environment. If there is enough space on the stack, that environment will be there,
* if not, it will be created in the heap. */
public void mkenv(int prevsize, int extrasize)
{
if (sp + extrasize + 3 > stack.length) {
mkheapenv(prevsize, extrasize);
return;
}
// If there is enough space on the stack, create the environment there.
// Add the extra environment entries
for (int i=0; i<extrasize; i++)
push(Unbound.UNBOUND);
int count = prevsize + extrasize;
int envstart = sp - count;
/* Stack environments are basically Fixnum pointers into the stack. */
int envptr = sp;
push(Fixnum.get(envstart)); // envptr
push(Fixnum.get(count)); // envptr + 1
push(env); // envptr + 2
env = Fixnum.get(envptr);
bp = sp;
}
/** Create a new heap environment ab initio */
private void mkheapenv(int prevsize, int extrasize)
{
// First, convert what will become the parent environment to a heap environment if it is not already one
env = HeapEnv.fromStackEnv(this, env);
int envstart = sp - prevsize;
// Create new heap environment and copy the environment values from the stack into it
HeapEnv nenv = new HeapEnv(prevsize + extrasize, env);
for (int i=0; i<prevsize; i++)
nenv.setEnv(i, stackIndex(envstart + i));
// Fill in extra environment entries with UNBOUND
for (int i=prevsize; i<prevsize+extrasize; i++)
nenv.setEnv(i, Unbound.UNBOUND);
bp = sp;
env = nenv;
}
/** move current environment to heap if needed */
public ArcObject heapenv()
{
env = HeapEnv.fromStackEnv(this, env);
return(env);
}
private ArcObject findenv(int depth)
{
ArcObject cenv = env;
while (depth-- > 0 && !cenv.is(Nil.NIL)) {
if (cenv instanceof Fixnum) {
int index = (int)((Fixnum)cenv).fixnum;
cenv = stackIndex(index+2);
} else {
HeapEnv e = (HeapEnv)cenv;
cenv = e.prevEnv();
}
}
return(cenv);
}
public ArcObject getenv(int depth, int index)
{
ArcObject cenv = findenv(depth);
if (cenv == Nil.NIL)
throw new NekoArcException("environment depth exceeded");
if (cenv instanceof Fixnum) {
int si = (int)((Fixnum)cenv).fixnum;
int start = (int)((Fixnum)stackIndex(si)).fixnum;
int size = (int)((Fixnum)stackIndex(si+1)).fixnum;
if (index > size)
throw new NekoArcException("stack environment index exceeded");
return(stackIndex(start+index));
}
return(((HeapEnv)cenv).getEnv(index));
}
public ArcObject setenv(int depth, int index, ArcObject value)
{
ArcObject cenv = findenv(depth);
if (cenv == Nil.NIL)
throw new NekoArcException("environment depth exceeded");
if (cenv instanceof Fixnum) {
int si = (int)((Fixnum)cenv).fixnum;
int start = (int)((Fixnum)stackIndex(si)).fixnum;
int size = (int)((Fixnum)stackIndex(si+1)).fixnum;
if (index > size)
throw new NekoArcException("stack environment index exceeded");
return(setStackIndex(start+index, value));
}
return(((HeapEnv)cenv).setEnv(index,value));
}
public ArcObject stackIndex(int index)
{
return(stack[index]);
}
public ArcObject setStackIndex(int index, ArcObject value)
{
return(stack[index] = value);
}
public void stackcheck(int required, final String message)
{
if (sp + required > stack.length) {
// Try to do stack gc first. If it fails, nothing for it
stackgc();
if (sp + required > stack.length)
throw new NekoArcException(message);
}
}
// Make a continuation on the stack. The new continuation is saved in the continuation register.
public void makecont(int ipoffset)
{
stackcheck(4, "stack overflow while creating continuation");
int newip = ip + ipoffset;
push(Fixnum.get(newip));
push(Fixnum.get(bp));
push(env);
push(cont);
cont = Fixnum.get(sp);
+ bp = sp;
}
public void restorecont()
{
restorecont(this);
}
// Restore continuation
public void restorecont(Callable caller)
{
if (cont instanceof Fixnum) {
sp = (int)((Fixnum)cont).fixnum;
cont = pop();
setenvreg(pop());
setBP((int)((Fixnum)pop()).fixnum);
setIP((int)((Fixnum)pop()).fixnum);
} else if (cont instanceof Continuation) {
Continuation ct = (Continuation)cont;
-// if (ct.stackReq() + sp > stack.length) {
-// stackgc();
-// if (ct.stackReq() + sp > stack.length)
-// throw new NekoArcException("stack overflow while restoring heap continuation");
-// }
ct.restore(this, caller);
} else if (cont.is(Nil.NIL)) {
// If we have no continuation, that was an attempt to return from the topmost
// level and we should halt the machine.
halt();
} else {
throw new NekoArcException("invalid continuation");
}
}
public void setenvreg(ArcObject env)
{
this.env = env;
}
public int getBP()
{
return bp;
}
public void setBP(int bp)
{
this.bp = bp;
}
public ArcObject getCont()
{
return cont;
}
public void setCont(ArcObject cont)
{
this.cont = cont;
}
@Override
public CallSync sync()
{
return(caller);
}
}
|
dido/arcueid
|
907c93469675df764d33cffed75a673f97d380a6
|
further tests for various cases when stack envs and conts go to the heap
|
diff --git a/java/test/org/arcueidarc/nekoarc/vm/HeapContinuationTest.java b/java/test/org/arcueidarc/nekoarc/vm/HeapContinuationTest.java
index 22c7862..4d74daa 100644
--- a/java/test/org/arcueidarc/nekoarc/vm/HeapContinuationTest.java
+++ b/java/test/org/arcueidarc/nekoarc/vm/HeapContinuationTest.java
@@ -1,80 +1,168 @@
package org.arcueidarc.nekoarc.vm;
import static org.junit.Assert.*;
import org.arcueidarc.nekoarc.HeapContinuation;
import org.arcueidarc.nekoarc.HeapEnv;
import org.arcueidarc.nekoarc.Nil;
+import org.arcueidarc.nekoarc.types.ArcObject;
+import org.arcueidarc.nekoarc.types.Closure;
import org.arcueidarc.nekoarc.types.Fixnum;
import org.junit.Test;
public class HeapContinuationTest
{
/** First we try to invent a HeapContinuation out of whole cloth. */
@Test
public void test()
{
HeapContinuation hc;
// Prepare an environment
HeapEnv env = new HeapEnv(3, Nil.NIL);
env.setEnv(0, Fixnum.get(4));
env.setEnv(1, Fixnum.get(5));
env.setEnv(2, Fixnum.get(6));
// Synthetic HeapContinuation
hc = new HeapContinuation(3, // 3 stack elements
Nil.NIL, // previous continuation
env, // environment
20); // saved IP
// Stack elements
hc.setIndex(0, Fixnum.get(1));
hc.setIndex(1, Fixnum.get(2));
hc.setIndex(2, Fixnum.get(3));
// Code:
// env 2 0 0; lde0 0; push; lde0 1; apply 1; ret; hlt; hlt; hlt; hlt; hlt;
// add everything already on the stack to the value applied to the continuation, get the
// stuff in the environment and add it too, and return the sum.
// add; add; add; push; lde0 0; add; push; lde0 1; add; push; lde0 2; add; ret
byte inst[] = { (byte)0xca, 0x02, 0x00, 0x00, // env 1 0 0
0x69, 0x00, // lde0 0 ; value (fixnum)
0x01, // push
0x69, 0x01, // lde0 1 ; continuation
0x4c, 0x01, // apply 1
0x0d, // ret
0x14, // hlt
0x14, // hlt
0x14, // hlt
0x14, // hlt
0x14, // hlt
0x14, // hlt
0x14, // hlt
0x14, // hlt
0x15, // add ; continuation ip address
0x15, // add
0x15, // add
0x01, // push
0x69, 0x00, // lde0 0
0x15, // add
0x01, // push
0x69, 0x01, // lde0 1
0x15, // add
0x01, // push
0x69, 0x02, // lde0 2
0x15, // add
0x0d, // ret
};
VirtualMachine vm = new VirtualMachine(1024);
vm.load(inst, 0);
vm.setargc(2);
vm.push(Fixnum.get(7));
vm.push(hc);
vm.setAcc(Nil.NIL);
assertTrue(vm.runnable());
vm.run();
assertFalse(vm.runnable());
assertEquals(28, ((Fixnum)vm.getAcc()).fixnum);
}
+ /** Next, we make a function that recurses several times, essentially
+ * (afn (x) (if (is x 0) 0 (+ (self (- x 1)) 2)))
+ * If stack space is very limited on the VM, the continuations that the recursive calls need to make should
+ * eventually migrate from the stack to the heap.
+ */
+ @Test
+ public void test2()
+ {
+ // env 1 0 0; lde0 0; push; ldi 0; is; jf L1; ldi 2; ret;
+ // L1: cont L2; lde0 0; push; ldi 1; sub; push; ldl 0; apply 1; L2: push; add; ret
+ byte inst[] = { (byte)0xca, 0x01, 0x00, 0x00, // env 1 0 0
+ 0x69, 0x00, // lde0 0
+ 0x01, // push
+ 0x44, 0x00, 0x00, 0x00, 0x00, // ldi 0
+ 0x1f, // is
+ 0x50, 0x06, 0x00, 0x00, 0x00, // jf L1 (6)
+ 0x44, 0x00, 0x00, 0x00, 0x00, // ldi 0
+ 0x0d, // ret
+ (byte)0x89, 0x11, 0x00, 0x00, 0x00, // L1: cont L2 (0x11)
+ 0x69, 0x00, // lde0 0
+ 0x01, // push
+ 0x44, 0x01, 0x00, 0x00, 0x00, // ldi 1
+ 0x16, // sub
+ 0x01, // push
+ 0x43, 0x00, 0x00, 0x00, 0x00, // ldl 0
+ 0x4c, 0x01, // apply 1
+ 0x01, // L2: push
+ 0x44, 0x02, 0x00, 0x00, 0x00, // ldi 2
+ 0x15, // add
+ 0x0d // ret
+ };
+ VirtualMachine vm = new VirtualMachine(4);
+ ArcObject literals[] = new ArcObject[1];
+ literals[0] = new Closure(Nil.NIL, Fixnum.get(0));
+ vm.load(inst, 0, literals);
+ vm.setargc(1);
+ vm.push(Fixnum.get(100));
+ vm.setAcc(literals[0]);
+ assertTrue(vm.runnable());
+ vm.run();
+ assertFalse(vm.runnable());
+ assertEquals(200, ((Fixnum)vm.getAcc()).fixnum);
+ }
+
+ /** Next, we make a slight variation
+ * (afn (x) (if (is x 0) 0 (+ 2 (self (- x 1)))))
+ */
+ @Test
+ public void test3()
+ {
+ // env 1 0 0; lde0 0; push; ldi 0; is; jf L1; ldi 2; ret;
+ // L1: cont L2; lde0 0; push; ldi 1; sub; push; ldl 0; apply 1; L2: push; add; ret
+ byte inst[] = { (byte)0xca, 0x01, 0x00, 0x00, // env 1 0 0
+ 0x69, 0x00, // lde0 0
+ 0x01, // push
+ 0x44, 0x00, 0x00, 0x00, 0x00, // ldi 0
+ 0x1f, // is
+ 0x50, 0x06, 0x00, 0x00, 0x00, // jf L1 (6)
+ 0x44, 0x00, 0x00, 0x00, 0x00, // ldi 0
+ 0x0d, // ret
+ (byte)0x89, 0x17, 0x00, 0x00, 0x00, // L1: cont L2 (0x17)
+ 0x44, 0x02, 0x00, 0x00, 0x00, // ldi 2
+ 0x01, // push
+ 0x69, 0x00, // lde0 0
+ 0x01, // push
+ 0x44, 0x01, 0x00, 0x00, 0x00, // ldi 1
+ 0x16, // sub
+ 0x01, // push
+ 0x43, 0x00, 0x00, 0x00, 0x00, // ldl 0
+ 0x4c, 0x01, // apply 1
+ 0x15, // L2: add
+ 0x0d // ret
+ };
+ VirtualMachine vm = new VirtualMachine(6);
+ ArcObject literals[] = new ArcObject[1];
+ literals[0] = new Closure(Nil.NIL, Fixnum.get(0));
+ vm.load(inst, 0, literals);
+ vm.setargc(1);
+ vm.push(Fixnum.get(100));
+ vm.setAcc(literals[0]);
+ assertTrue(vm.runnable());
+ vm.run();
+ assertFalse(vm.runnable());
+ assertEquals(200, ((Fixnum)vm.getAcc()).fixnum);
+ }
+
}
|
dido/arcueid
|
e1c86bff1a16d5c81b1c432f2aa6b2a1078f281c
|
compute (fib 25)
|
diff --git a/java/test/org/arcueidarc/nekoarc/vm/FibonacciTest.java b/java/test/org/arcueidarc/nekoarc/vm/FibonacciTest.java
index b47a4dd..fb73e7d 100644
--- a/java/test/org/arcueidarc/nekoarc/vm/FibonacciTest.java
+++ b/java/test/org/arcueidarc/nekoarc/vm/FibonacciTest.java
@@ -1,72 +1,72 @@
package org.arcueidarc.nekoarc.vm;
import static org.junit.Assert.*;
import org.arcueidarc.nekoarc.types.ArcObject;
import org.arcueidarc.nekoarc.types.Fixnum;
import org.arcueidarc.nekoarc.types.Closure;
import org.arcueidarc.nekoarc.Nil;
import org.junit.Test;
public class FibonacciTest
{
/* This is a recursive Fibonacci test, essentially (afn (x) (if (is x 0) 1 (is x 1) 1 (+ (self (- x 1)) (self (- x 2)))))
* Since this isn't tail recursive it runs in exponential time and will use up a lot of stack space for continuations.
* If we don't migrate continuations to the heap this will very quickly use up stack space if it's set low enough.
*/
@Test
public void test()
{
// env 1 0 0; lde0 0; push; ldi 0; is; jf xxx; ldi 1; ret; lde0 0; push ldi 1; is; jf xxx; ldi 1; ret;
// cont xxx; lde0 0; push; ldi 1; sub; push; ldl 0; apply 1; push;
// cont xxx; lde0 0; push; ldi 2; sub; push; ldl 0; apply 1; add; ret
byte inst[] = { (byte)0xca, 0x01, 0x00, 0x00, // env 1 0 0
0x69, 0x00, // lde0 0
0x01, // push
0x44, 0x00, 0x00, 0x00, 0x00, // ldi 0
0x1f, // is
0x50, 0x06, 0x00, 0x00, 0x00, // jf L1 (6)
0x44, 0x01, 0x00, 0x00, 0x00, // ldi 1
0x0d, // ret
0x69, 0x00, // L1: lde0 0
0x01, // push
0x44, 0x01, 0x00, 0x00, 0x00, // ldi 1
0x1f, // is
0x50, 0x06, 0x00, 0x00, 0x00, // jf L2 (6)
0x44, 0x01, 0x00, 0x00, 0x00, // ldi 1
0x0d, // ret
(byte)0x89, 0x11, 0x00, 0x00, 0x00, // L2: cont L3 (0x11)
0x69, 0x00, // lde0 0
0x01, // push
0x44, 0x01, 0x00, 0x00, 0x00, // ldi 1
0x16, // sub
0x01, // push
0x43, 0x00, 0x00, 0x00, 0x00, // ldl 0
0x4c, 0x01, // apply 1
0x01, // L3: push
(byte)0x89, 0x11, 0x00, 0x00, 0x00, // cont L4 (0x11)
0x69, 0x00, // lde0 0
0x01, // push
0x44, 0x02, 0x00, 0x00, 0x00, // ldi 2
0x16, // sub
0x01, // push
0x43, 0x00, 0x00, 0x00, 0x00, // ldl 0
0x4c, 0x01, // apply 1
0x15, // add
0x0d // ret
};
VirtualMachine vm = new VirtualMachine(12);
ArcObject literals[] = new ArcObject[1];
literals[0] = new Closure(Nil.NIL, Fixnum.get(0));
vm.load(inst, 0, literals);
vm.setargc(1);
- vm.push(Fixnum.get(8));
+ vm.push(Fixnum.get(25));
vm.setAcc(Nil.NIL);
assertTrue(vm.runnable());
vm.run();
assertFalse(vm.runnable());
- assertEquals(34, ((Fixnum)vm.getAcc()).fixnum);
+ assertEquals(121393, ((Fixnum)vm.getAcc()).fixnum);
}
}
|
dido/arcueid
|
0175c29e66e181840cb963121b4f8cd664d2d8cd
|
try to move continuations to the heap on stackgc (still buggy)
|
diff --git a/java/src/org/arcueidarc/nekoarc/vm/VirtualMachine.java b/java/src/org/arcueidarc/nekoarc/vm/VirtualMachine.java
index ddcf24d..8f8d300 100644
--- a/java/src/org/arcueidarc/nekoarc/vm/VirtualMachine.java
+++ b/java/src/org/arcueidarc/nekoarc/vm/VirtualMachine.java
@@ -1,683 +1,684 @@
package org.arcueidarc.nekoarc.vm;
import org.arcueidarc.nekoarc.Continuation;
-// import org.arcueidarc.nekoarc.HeapContinuation;
+import org.arcueidarc.nekoarc.HeapContinuation;
import org.arcueidarc.nekoarc.HeapEnv;
import org.arcueidarc.nekoarc.NekoArcException;
import org.arcueidarc.nekoarc.Nil;
import org.arcueidarc.nekoarc.Unbound;
import org.arcueidarc.nekoarc.types.ArcObject;
import org.arcueidarc.nekoarc.types.Fixnum;
import org.arcueidarc.nekoarc.types.Symbol;
import org.arcueidarc.nekoarc.util.CallSync;
import org.arcueidarc.nekoarc.util.Callable;
import org.arcueidarc.nekoarc.util.ObjectMap;
import org.arcueidarc.nekoarc.vm.instruction.*;
public class VirtualMachine implements Callable
{
private int sp; // stack pointer
private int bp; // base pointer
private ArcObject env; // environment pointer
private ArcObject cont; // continuation pointer
private ArcObject[] stack; // stack
private final CallSync caller;
private int ip; // instruction pointer
private byte[] code;
private boolean runnable;
private ArcObject acc; // accumulator
private ArcObject[] literals;
private int argc; // argument counter for current function
private static final INVALID NOINST = new INVALID();
private static final Instruction[] jmptbl = {
new NOP(), // 0x00
new PUSH(), // 0x01
new POP(), // 0x02
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
new RET(), // 0x0d
NOINST,
NOINST,
NOINST,
new NO(), // 0x11
new TRUE(), // 0x12
new NIL(), // 0x13
new HLT(), // 0x14
new ADD(), // 0x15
new SUB(), // 0x16
new MUL(), // 0x17
new DIV(), // 0x18
new CONS(), // 0x19
new CAR(), // 0x1a
new CDR(), // 0x1b
new SCAR(), // 0x1c
new SCDR(), // 0x1d
NOINST,
new IS(), // 0x1f
NOINST,
NOINST,
new DUP(), // 0x22
NOINST, // 0x23
new CONSR(), // 0x24
NOINST,
new DCAR(), // 0x26
new DCDR(), // 0x27
new SPL(), // 0x28
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
new LDL(), // 0x43
new LDI(), // 0x44
new LDG(), // 0x45
new STG(), // 0x46
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
new APPLY(), // 0x4c
new CLS(), // 0x4d,
new JMP(), // 0x4e
new JT(), // 0x4f
new JF(), // 0x50
new JBND(), // 0x51
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
new MENV(), // 0x65
NOINST,
NOINST,
NOINST,
new LDE0(), // 0x69
new STE0(), // 0x6a
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
new LDE(), // 0x87
new STE(), // 0x88
new CONT(), // 0x89
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
new ENV(), // 0xca
new ENVR(), // 0xcb
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
};
private ObjectMap<Symbol, ArcObject> genv = new ObjectMap<Symbol, ArcObject>();
public VirtualMachine(int stacksize)
{
sp = bp = 0;
stack = new ArcObject[stacksize];
ip = 0;
code = null;
runnable = true;
env = Nil.NIL;
cont = Nil.NIL;
setAcc(Nil.NIL);
caller = new CallSync();
}
public void load(final byte[] instructions, int ip, final ArcObject[] literals)
{
this.code = instructions;
this.literals = literals;
this.ip = ip;
}
public void load(final byte[] instructions, int ip)
{
load(instructions, ip, null);
}
public void halt()
{
runnable = false;
}
public void nextI()
{
ip++;
}
/**
* Attempt to garbage collect the stack, after Richard A. Kelsey, "Tail Recursive Stack Disciplines for an Interpreter"
* Basically, the only things on the stack that are garbage collected are environments and continuations.
* The algorithm here works by copying all environments and continuations from the stack to the heap. When that's done it will move the stack pointer
* to the top of the stack.
* 1. Start with the environment register. Move that environment and all of its children to the heap.
* 2. Continue with the continuation register. Copy the current continuation into the heap.
* 3. Compact the stack by moving the remainder of the non-stack/non-continuation elements to the heap.
*/
private void stackgc()
{
int stackbottom = -1;
if (env instanceof Fixnum) {
int si = (int)((Fixnum)env).fixnum;
stackbottom = (int)((Fixnum)stackIndex(si)).fixnum;
env = HeapEnv.fromStackEnv(this, env);
}
if (cont instanceof Fixnum) {
+ int[] deepest = {0};
// If the current continuation is on the stack move it to the heap
-// ArcObject nc = HeapContinuation.fromStackCont(this, (Fixnum)cont);
-// this.setCont(nc);
-// stackbottom = 0;
- stackbottom = (int)((Fixnum)cont).fixnum + 1;
+ ArcObject nc = HeapContinuation.fromStackCont(this, cont, deepest);
+ this.setCont(nc);
+ stackbottom = deepest[0];
+// stackbottom = (int)((Fixnum)cont).fixnum + 1;
}
// Garbage collection failed to produce memory
if (stackbottom < 0 || stackbottom > stack.length || stackbottom == bp)
return;
// move what we can of the used portion of the stack to the bottom.
for (int i=0; i<sp - bp - 1; i++)
setStackIndex(stackbottom + i, stackIndex(bp + i));
sp = stackbottom + (sp - bp - 1);
bp = stackbottom;
}
public void push(ArcObject obj)
{
for (;;) {
try {
stack[sp++] = obj;
return;
} catch (ArrayIndexOutOfBoundsException e) {
// We can try to garbage collect the stack
stackgc();
if (sp >= stack.length)
throw new NekoArcException("stack overflow");
}
}
}
public ArcObject pop()
{
return(stack[--sp]);
}
public void run()
throws NekoArcException
{
while (runnable) {
jmptbl[(int)code[ip++] & 0xff].invoke(this);
}
}
// Four-byte instruction arguments (most everything else). Little endian.
public int instArg()
{
long val = 0;
int data;
for (int i=0; i<4; i++) {
data = (((int)code[ip++]) & 0xff);
val |= data << i*8;
}
return((int)((val << 1) >> 1));
}
// one-byte instruction arguments (LDE/STE/ENV, etc.)
public byte smallInstArg()
{
return(code[ip++]);
}
public ArcObject getAcc()
{
return acc;
}
public void setAcc(ArcObject acc)
{
this.acc = acc;
}
public boolean runnable()
{
return(this.runnable);
}
public boolean setrunnable(boolean runstate)
{
this.runnable = runstate;
return(runstate);
}
public ArcObject literal(int offset)
{
return(literals[offset]);
}
public int getIP()
{
return ip;
}
public void setIP(int ip)
{
this.ip = ip;
}
public int getSP()
{
return(sp);
}
public void setSP(int sp)
{
this.sp = sp;
}
// add or replace a global binding
public ArcObject bind(Symbol sym, ArcObject binding)
{
genv.put(sym, binding);
return(binding);
}
public ArcObject value(Symbol sym)
{
if (!genv.containsKey(sym))
throw new NekoArcException("Unbound symbol " + sym);
return(genv.get(sym));
}
public int argc()
{
return(argc);
}
public int setargc(int ac)
{
return(argc = ac);
}
public void argcheck(int minarg, int maxarg)
{
if (argc() < minarg)
throw new NekoArcException("too few arguments, at least " + minarg + " required, " + argc() + " passed");
if (maxarg >= 0 && argc() > maxarg)
throw new NekoArcException("too many arguments, at most " + maxarg + " allowed, " + argc() + " passed");
}
public void argcheck(int arg)
{
argcheck(arg, arg);
}
/* Create an environment. If there is enough space on the stack, that environment will be there,
* if not, it will be created in the heap. */
public void mkenv(int prevsize, int extrasize)
{
if (sp + extrasize + 3 > stack.length) {
mkheapenv(prevsize, extrasize);
return;
}
// If there is enough space on the stack, create the environment there.
// Add the extra environment entries
for (int i=0; i<extrasize; i++)
push(Unbound.UNBOUND);
int count = prevsize + extrasize;
int envstart = sp - count;
/* Stack environments are basically Fixnum pointers into the stack. */
int envptr = sp;
push(Fixnum.get(envstart)); // envptr
push(Fixnum.get(count)); // envptr + 1
push(env); // envptr + 2
env = Fixnum.get(envptr);
bp = sp;
}
/** Create a new heap environment ab initio */
private void mkheapenv(int prevsize, int extrasize)
{
// First, convert what will become the parent environment to a heap environment if it is not already one
env = HeapEnv.fromStackEnv(this, env);
int envstart = sp - prevsize;
// Create new heap environment and copy the environment values from the stack into it
HeapEnv nenv = new HeapEnv(prevsize + extrasize, env);
for (int i=0; i<prevsize; i++)
nenv.setEnv(i, stackIndex(envstart + i));
// Fill in extra environment entries with UNBOUND
for (int i=prevsize; i<prevsize+extrasize; i++)
nenv.setEnv(i, Unbound.UNBOUND);
bp = sp;
env = nenv;
}
/** move current environment to heap if needed */
public ArcObject heapenv()
{
env = HeapEnv.fromStackEnv(this, env);
return(env);
}
private ArcObject findenv(int depth)
{
ArcObject cenv = env;
while (depth-- > 0 && !cenv.is(Nil.NIL)) {
if (cenv instanceof Fixnum) {
int index = (int)((Fixnum)cenv).fixnum;
cenv = stackIndex(index+2);
} else {
HeapEnv e = (HeapEnv)cenv;
cenv = e.prevEnv();
}
}
return(cenv);
}
public ArcObject getenv(int depth, int index)
{
ArcObject cenv = findenv(depth);
if (cenv == Nil.NIL)
throw new NekoArcException("environment depth exceeded");
if (cenv instanceof Fixnum) {
int si = (int)((Fixnum)cenv).fixnum;
int start = (int)((Fixnum)stackIndex(si)).fixnum;
int size = (int)((Fixnum)stackIndex(si+1)).fixnum;
if (index > size)
throw new NekoArcException("stack environment index exceeded");
return(stackIndex(start+index));
}
return(((HeapEnv)cenv).getEnv(index));
}
public ArcObject setenv(int depth, int index, ArcObject value)
{
ArcObject cenv = findenv(depth);
if (cenv == Nil.NIL)
throw new NekoArcException("environment depth exceeded");
if (cenv instanceof Fixnum) {
int si = (int)((Fixnum)cenv).fixnum;
int start = (int)((Fixnum)stackIndex(si)).fixnum;
int size = (int)((Fixnum)stackIndex(si+1)).fixnum;
if (index > size)
throw new NekoArcException("stack environment index exceeded");
return(setStackIndex(start+index, value));
}
return(((HeapEnv)cenv).setEnv(index,value));
}
public ArcObject stackIndex(int index)
{
return(stack[index]);
}
public ArcObject setStackIndex(int index, ArcObject value)
{
return(stack[index] = value);
}
public void stackcheck(int required, final String message)
{
if (sp + required > stack.length) {
// Try to do stack gc first. If it fails, nothing for it
stackgc();
if (sp + required > stack.length)
throw new NekoArcException(message);
}
}
// Make a continuation on the stack. The new continuation is saved in the continuation register.
public void makecont(int ipoffset)
{
stackcheck(4, "stack overflow while creating continuation");
int newip = ip + ipoffset;
push(Fixnum.get(newip));
push(Fixnum.get(bp));
push(env);
push(cont);
cont = Fixnum.get(sp);
}
public void restorecont()
{
restorecont(this);
}
// Restore continuation
public void restorecont(Callable caller)
{
if (cont instanceof Fixnum) {
sp = (int)((Fixnum)cont).fixnum;
cont = pop();
setenvreg(pop());
setBP((int)((Fixnum)pop()).fixnum);
setIP((int)((Fixnum)pop()).fixnum);
} else if (cont instanceof Continuation) {
Continuation ct = (Continuation)cont;
// if (ct.stackReq() + sp > stack.length) {
// stackgc();
// if (ct.stackReq() + sp > stack.length)
// throw new NekoArcException("stack overflow while restoring heap continuation");
// }
ct.restore(this, caller);
} else if (cont.is(Nil.NIL)) {
// If we have no continuation, that was an attempt to return from the topmost
// level and we should halt the machine.
halt();
} else {
throw new NekoArcException("invalid continuation");
}
}
public void setenvreg(ArcObject env)
{
this.env = env;
}
public int getBP()
{
return bp;
}
public void setBP(int bp)
{
this.bp = bp;
}
public ArcObject getCont()
{
return cont;
}
public void setCont(ArcObject cont)
{
this.cont = cont;
}
@Override
public CallSync sync()
{
return(caller);
}
}
|
dido/arcueid
|
629e25bce1627384272dd1f7f938e9fc974a2eb7
|
heap continuations only include data of the current function call
|
diff --git a/java/src/org/arcueidarc/nekoarc/HeapContinuation.java b/java/src/org/arcueidarc/nekoarc/HeapContinuation.java
index ba7cdc9..6806552 100644
--- a/java/src/org/arcueidarc/nekoarc/HeapContinuation.java
+++ b/java/src/org/arcueidarc/nekoarc/HeapContinuation.java
@@ -1,58 +1,99 @@
package org.arcueidarc.nekoarc;
import org.arcueidarc.nekoarc.types.ArcObject;
import org.arcueidarc.nekoarc.types.Fixnum;
import org.arcueidarc.nekoarc.types.Symbol;
import org.arcueidarc.nekoarc.types.Vector;
import org.arcueidarc.nekoarc.util.Callable;
import org.arcueidarc.nekoarc.vm.VirtualMachine;
public class HeapContinuation extends Vector implements Continuation
{
public static final ArcObject TYPE = Symbol.intern("continuation");
+ private final ArcObject prevcont;
+ private final ArcObject env;
+ private final int ipoffset;
- public HeapContinuation(int size)
+ public HeapContinuation(int size, ArcObject pcont, ArcObject e, int ip)
{
super(size);
+ prevcont = pcont;
+ env = e;
+ ipoffset = ip;
}
-
@Override
/**
- * Restore a stack-based continuation.
+ * Move heap continuation to stack for restoration.
*/
public void restore(VirtualMachine vm, Callable cc)
{
- Fixnum c = Fixnum.get(this.length());
- for (int i=0; i<this.length(); i++)
- vm.setStackIndex(i, index(i));
- vm.setSP(this.length());
- vm.setCont(c);
- vm.restorecont();
+ int svsize = this.length();
+
+ vm.stackcheck(svsize + 4, "stack overflow while restoring heap continuation");
+
+ int bp = vm.getSP();
+ // push the saved stack values back to the stack
+ for (int i=0; i<svsize; i++)
+ vm.push(index(i));
+ // push the saved instruction pointer
+ vm.push(Fixnum.get(ipoffset));
+ // push the new base pointer
+ vm.push(Fixnum.get(bp));
+ // push the saved environment
+ vm.push(env);
+ // push the previous continuation
+ vm.push(prevcont);
+ vm.setCont(Fixnum.get(vm.getSP()));
}
- public static HeapContinuation fromStackCont(VirtualMachine vm, ArcObject sc)
+ public static ArcObject fromStackCont(VirtualMachine vm, ArcObject sc)
{
+ return(fromStackCont(vm, sc, null));
+ }
+
+ /**
+ * Create a new heap continuation from a stack-based continuation.
+ * A stack continuation is a pointer into the stack, such that
+ * [cont-1] -> previous continuation
+ * [cont-2] -> environment
+ * [cont-3] -> base pointer
+ * [cont-4] -> instruction pointer offset
+ * [cont-(5+n)] -> saved stack elements up to saved base pointer position
+ * This function copies all of this relevant information to the a new HeapContinuation so it can later be restored
+ */
+ public static ArcObject fromStackCont(VirtualMachine vm, ArcObject sc, int[] deepest)
+ {
+ if (sc instanceof HeapContinuation || sc.is(Nil.NIL))
+ return(sc);
int cc = (int)((Fixnum)sc).fixnum;
- HeapContinuation c = new HeapContinuation(cc);
- for (int i=0; i<cc; i++)
- c.setIndex(i, vm.stackIndex(i));
+ // Calculate the size of the actual continuation based on the saved base pointer
+ int bp = (int)((Fixnum)vm.stackIndex(cc-3)).fixnum;
+ int svsize = cc - bp - 4;
+ if (deepest != null)
+ deepest[0] = bp;
+ // Turn previous continuation into a heap-based one too
+ ArcObject pco = vm.stackIndex(cc-1);
+ pco = fromStackCont(vm, pco, deepest);
+ HeapContinuation c = new HeapContinuation(svsize, pco, HeapEnv.fromStackEnv(vm, vm.stackIndex(cc-2)), (int)((Fixnum)vm.stackIndex(cc-4)).fixnum);
+
+ for (int i=0; i<svsize; i++)
+ c.setIndex(i, vm.stackIndex(bp + i));
return(c);
}
-
@Override
public int requiredArgs()
{
return(1);
}
/** The application of a continuation -- this will set itself as the current continuation,
* ready to be restored just as the invokethread terminates. */
@Override
public ArcObject invoke(InvokeThread thr)
{
thr.vm.setCont(this);
return(thr.getenv(0, 0));
}
}
|
dido/arcueid
|
cd8743e8c11b6405dccbc4921ea5c6407abcb55b
|
stack checks, heap environment creation changes
|
diff --git a/java/src/org/arcueidarc/nekoarc/vm/VirtualMachine.java b/java/src/org/arcueidarc/nekoarc/vm/VirtualMachine.java
index 8cf0e0e..ddcf24d 100644
--- a/java/src/org/arcueidarc/nekoarc/vm/VirtualMachine.java
+++ b/java/src/org/arcueidarc/nekoarc/vm/VirtualMachine.java
@@ -1,674 +1,683 @@
package org.arcueidarc.nekoarc.vm;
import org.arcueidarc.nekoarc.Continuation;
// import org.arcueidarc.nekoarc.HeapContinuation;
import org.arcueidarc.nekoarc.HeapEnv;
import org.arcueidarc.nekoarc.NekoArcException;
import org.arcueidarc.nekoarc.Nil;
import org.arcueidarc.nekoarc.Unbound;
import org.arcueidarc.nekoarc.types.ArcObject;
import org.arcueidarc.nekoarc.types.Fixnum;
import org.arcueidarc.nekoarc.types.Symbol;
import org.arcueidarc.nekoarc.util.CallSync;
import org.arcueidarc.nekoarc.util.Callable;
import org.arcueidarc.nekoarc.util.ObjectMap;
import org.arcueidarc.nekoarc.vm.instruction.*;
public class VirtualMachine implements Callable
{
private int sp; // stack pointer
private int bp; // base pointer
private ArcObject env; // environment pointer
private ArcObject cont; // continuation pointer
private ArcObject[] stack; // stack
private final CallSync caller;
private int ip; // instruction pointer
private byte[] code;
private boolean runnable;
private ArcObject acc; // accumulator
private ArcObject[] literals;
private int argc; // argument counter for current function
private static final INVALID NOINST = new INVALID();
private static final Instruction[] jmptbl = {
new NOP(), // 0x00
new PUSH(), // 0x01
new POP(), // 0x02
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
new RET(), // 0x0d
NOINST,
NOINST,
NOINST,
new NO(), // 0x11
new TRUE(), // 0x12
new NIL(), // 0x13
new HLT(), // 0x14
new ADD(), // 0x15
new SUB(), // 0x16
new MUL(), // 0x17
new DIV(), // 0x18
new CONS(), // 0x19
new CAR(), // 0x1a
new CDR(), // 0x1b
new SCAR(), // 0x1c
new SCDR(), // 0x1d
NOINST,
new IS(), // 0x1f
NOINST,
NOINST,
new DUP(), // 0x22
NOINST, // 0x23
new CONSR(), // 0x24
NOINST,
new DCAR(), // 0x26
new DCDR(), // 0x27
new SPL(), // 0x28
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
new LDL(), // 0x43
new LDI(), // 0x44
new LDG(), // 0x45
new STG(), // 0x46
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
new APPLY(), // 0x4c
new CLS(), // 0x4d,
new JMP(), // 0x4e
new JT(), // 0x4f
new JF(), // 0x50
new JBND(), // 0x51
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
new MENV(), // 0x65
NOINST,
NOINST,
NOINST,
new LDE0(), // 0x69
new STE0(), // 0x6a
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
new LDE(), // 0x87
new STE(), // 0x88
new CONT(), // 0x89
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
new ENV(), // 0xca
new ENVR(), // 0xcb
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
};
private ObjectMap<Symbol, ArcObject> genv = new ObjectMap<Symbol, ArcObject>();
public VirtualMachine(int stacksize)
{
sp = bp = 0;
stack = new ArcObject[stacksize];
ip = 0;
code = null;
runnable = true;
env = Nil.NIL;
cont = Nil.NIL;
setAcc(Nil.NIL);
caller = new CallSync();
}
public void load(final byte[] instructions, int ip, final ArcObject[] literals)
{
this.code = instructions;
this.literals = literals;
this.ip = ip;
}
public void load(final byte[] instructions, int ip)
{
load(instructions, ip, null);
}
public void halt()
{
runnable = false;
}
public void nextI()
{
ip++;
}
/**
* Attempt to garbage collect the stack, after Richard A. Kelsey, "Tail Recursive Stack Disciplines for an Interpreter"
* Basically, the only things on the stack that are garbage collected are environments and continuations.
* The algorithm here works by copying all environments and continuations from the stack to the heap. When that's done it will move the stack pointer
* to the top of the stack.
* 1. Start with the environment register. Move that environment and all of its children to the heap.
* 2. Continue with the continuation register. Copy the current continuation into the heap.
* 3. Compact the stack by moving the remainder of the non-stack/non-continuation elements to the heap.
*/
private void stackgc()
{
int stackbottom = -1;
if (env instanceof Fixnum) {
int si = (int)((Fixnum)env).fixnum;
stackbottom = (int)((Fixnum)stackIndex(si)).fixnum;
- env = HeapEnv.fromStackEnv(this, si);
+ env = HeapEnv.fromStackEnv(this, env);
}
if (cont instanceof Fixnum) {
// If the current continuation is on the stack move it to the heap
// ArcObject nc = HeapContinuation.fromStackCont(this, (Fixnum)cont);
// this.setCont(nc);
// stackbottom = 0;
-// stackbottom = (int)((Fixnum)cont).fixnum + 1;
+ stackbottom = (int)((Fixnum)cont).fixnum + 1;
}
// Garbage collection failed to produce memory
if (stackbottom < 0 || stackbottom > stack.length || stackbottom == bp)
return;
// move what we can of the used portion of the stack to the bottom.
for (int i=0; i<sp - bp - 1; i++)
setStackIndex(stackbottom + i, stackIndex(bp + i));
sp = stackbottom + (sp - bp - 1);
bp = stackbottom;
}
public void push(ArcObject obj)
{
for (;;) {
try {
stack[sp++] = obj;
return;
} catch (ArrayIndexOutOfBoundsException e) {
// We can try to garbage collect the stack
stackgc();
if (sp >= stack.length)
throw new NekoArcException("stack overflow");
}
}
}
public ArcObject pop()
{
return(stack[--sp]);
}
public void run()
throws NekoArcException
{
while (runnable) {
jmptbl[(int)code[ip++] & 0xff].invoke(this);
}
}
// Four-byte instruction arguments (most everything else). Little endian.
public int instArg()
{
long val = 0;
int data;
for (int i=0; i<4; i++) {
data = (((int)code[ip++]) & 0xff);
val |= data << i*8;
}
return((int)((val << 1) >> 1));
}
// one-byte instruction arguments (LDE/STE/ENV, etc.)
public byte smallInstArg()
{
return(code[ip++]);
}
public ArcObject getAcc()
{
return acc;
}
public void setAcc(ArcObject acc)
{
this.acc = acc;
}
public boolean runnable()
{
return(this.runnable);
}
public boolean setrunnable(boolean runstate)
{
this.runnable = runstate;
return(runstate);
}
public ArcObject literal(int offset)
{
return(literals[offset]);
}
public int getIP()
{
return ip;
}
public void setIP(int ip)
{
this.ip = ip;
}
public int getSP()
{
return(sp);
}
public void setSP(int sp)
{
this.sp = sp;
}
// add or replace a global binding
public ArcObject bind(Symbol sym, ArcObject binding)
{
genv.put(sym, binding);
return(binding);
}
public ArcObject value(Symbol sym)
{
if (!genv.containsKey(sym))
throw new NekoArcException("Unbound symbol " + sym);
return(genv.get(sym));
}
public int argc()
{
return(argc);
}
public int setargc(int ac)
{
return(argc = ac);
}
public void argcheck(int minarg, int maxarg)
{
if (argc() < minarg)
throw new NekoArcException("too few arguments, at least " + minarg + " required, " + argc() + " passed");
if (maxarg >= 0 && argc() > maxarg)
throw new NekoArcException("too many arguments, at most " + maxarg + " allowed, " + argc() + " passed");
}
public void argcheck(int arg)
{
argcheck(arg, arg);
}
/* Create an environment. If there is enough space on the stack, that environment will be there,
* if not, it will be created in the heap. */
public void mkenv(int prevsize, int extrasize)
{
if (sp + extrasize + 3 > stack.length) {
mkheapenv(prevsize, extrasize);
return;
}
// If there is enough space on the stack, create the environment there.
// Add the extra environment entries
for (int i=0; i<extrasize; i++)
push(Unbound.UNBOUND);
int count = prevsize + extrasize;
int envstart = sp - count;
/* Stack environments are basically Fixnum pointers into the stack. */
int envptr = sp;
push(Fixnum.get(envstart)); // envptr
push(Fixnum.get(count)); // envptr + 1
push(env); // envptr + 2
env = Fixnum.get(envptr);
bp = sp;
}
+ /** Create a new heap environment ab initio */
private void mkheapenv(int prevsize, int extrasize)
{
- // First, convert the parent environment to a heap environment if it is not already one
- if (env instanceof Fixnum)
- env = HeapEnv.fromStackEnv(this, (int)((Fixnum)env).fixnum);
+ // First, convert what will become the parent environment to a heap environment if it is not already one
+ env = HeapEnv.fromStackEnv(this, env);
int envstart = sp - prevsize;
// Create new heap environment and copy the environment values from the stack into it
HeapEnv nenv = new HeapEnv(prevsize + extrasize, env);
for (int i=0; i<prevsize; i++)
nenv.setEnv(i, stackIndex(envstart + i));
// Fill in extra environment entries with UNBOUND
for (int i=prevsize; i<prevsize+extrasize; i++)
nenv.setEnv(i, Unbound.UNBOUND);
bp = sp;
env = nenv;
}
/** move current environment to heap if needed */
public ArcObject heapenv()
{
- if (env instanceof Fixnum)
- env = HeapEnv.fromStackEnv(this, (int)((Fixnum)env).fixnum);
+ env = HeapEnv.fromStackEnv(this, env);
return(env);
}
private ArcObject findenv(int depth)
{
ArcObject cenv = env;
while (depth-- > 0 && !cenv.is(Nil.NIL)) {
if (cenv instanceof Fixnum) {
int index = (int)((Fixnum)cenv).fixnum;
cenv = stackIndex(index+2);
} else {
HeapEnv e = (HeapEnv)cenv;
cenv = e.prevEnv();
}
}
return(cenv);
}
public ArcObject getenv(int depth, int index)
{
ArcObject cenv = findenv(depth);
if (cenv == Nil.NIL)
throw new NekoArcException("environment depth exceeded");
if (cenv instanceof Fixnum) {
int si = (int)((Fixnum)cenv).fixnum;
int start = (int)((Fixnum)stackIndex(si)).fixnum;
int size = (int)((Fixnum)stackIndex(si+1)).fixnum;
if (index > size)
throw new NekoArcException("stack environment index exceeded");
return(stackIndex(start+index));
}
return(((HeapEnv)cenv).getEnv(index));
}
public ArcObject setenv(int depth, int index, ArcObject value)
{
ArcObject cenv = findenv(depth);
if (cenv == Nil.NIL)
throw new NekoArcException("environment depth exceeded");
if (cenv instanceof Fixnum) {
int si = (int)((Fixnum)cenv).fixnum;
int start = (int)((Fixnum)stackIndex(si)).fixnum;
int size = (int)((Fixnum)stackIndex(si+1)).fixnum;
if (index > size)
throw new NekoArcException("stack environment index exceeded");
return(setStackIndex(start+index, value));
}
return(((HeapEnv)cenv).setEnv(index,value));
}
public ArcObject stackIndex(int index)
{
return(stack[index]);
}
public ArcObject setStackIndex(int index, ArcObject value)
{
return(stack[index] = value);
}
- // Make a continuation on the stack. The new continuation is saved in the continuation register.
- public void makecont(int ipoffset)
+ public void stackcheck(int required, final String message)
{
- if (sp + 4 > stack.length) {
+ if (sp + required > stack.length) {
// Try to do stack gc first. If it fails, nothing for it
stackgc();
- if (sp + 4 > stack.length)
- throw new NekoArcException("stack overflow while creating continuation");
+ if (sp + required > stack.length)
+ throw new NekoArcException(message);
}
+ }
+ // Make a continuation on the stack. The new continuation is saved in the continuation register.
+ public void makecont(int ipoffset)
+ {
+ stackcheck(4, "stack overflow while creating continuation");
int newip = ip + ipoffset;
push(Fixnum.get(newip));
push(Fixnum.get(bp));
push(env);
push(cont);
cont = Fixnum.get(sp);
}
public void restorecont()
{
restorecont(this);
}
// Restore continuation
public void restorecont(Callable caller)
{
if (cont instanceof Fixnum) {
sp = (int)((Fixnum)cont).fixnum;
cont = pop();
setenvreg(pop());
setBP((int)((Fixnum)pop()).fixnum);
setIP((int)((Fixnum)pop()).fixnum);
} else if (cont instanceof Continuation) {
- ((Continuation)cont).restore(this, caller);
+ Continuation ct = (Continuation)cont;
+// if (ct.stackReq() + sp > stack.length) {
+// stackgc();
+// if (ct.stackReq() + sp > stack.length)
+// throw new NekoArcException("stack overflow while restoring heap continuation");
+// }
+ ct.restore(this, caller);
} else if (cont.is(Nil.NIL)) {
// If we have no continuation, that was an attempt to return from the topmost
// level and we should halt the machine.
halt();
} else {
throw new NekoArcException("invalid continuation");
}
}
public void setenvreg(ArcObject env)
{
this.env = env;
}
public int getBP()
{
return bp;
}
public void setBP(int bp)
{
this.bp = bp;
}
public ArcObject getCont()
{
return cont;
}
public void setCont(ArcObject cont)
{
this.cont = cont;
}
@Override
public CallSync sync()
{
return(caller);
}
}
|
dido/arcueid
|
6c4d0df432b4f2e8035f4913e379c9524c66e376
|
new HeapContinuation construction process
|
diff --git a/java/test/org/arcueidarc/nekoarc/vm/HeapContinuationTest.java b/java/test/org/arcueidarc/nekoarc/vm/HeapContinuationTest.java
index d5fe23b..22c7862 100644
--- a/java/test/org/arcueidarc/nekoarc/vm/HeapContinuationTest.java
+++ b/java/test/org/arcueidarc/nekoarc/vm/HeapContinuationTest.java
@@ -1,81 +1,80 @@
package org.arcueidarc.nekoarc.vm;
import static org.junit.Assert.*;
import org.arcueidarc.nekoarc.HeapContinuation;
import org.arcueidarc.nekoarc.HeapEnv;
import org.arcueidarc.nekoarc.Nil;
import org.arcueidarc.nekoarc.types.Fixnum;
import org.junit.Test;
public class HeapContinuationTest
{
/** First we try to invent a HeapContinuation out of whole cloth. */
@Test
public void test()
{
HeapContinuation hc;
// Prepare an environment
HeapEnv env = new HeapEnv(3, Nil.NIL);
env.setEnv(0, Fixnum.get(4));
env.setEnv(1, Fixnum.get(5));
env.setEnv(2, Fixnum.get(6));
// Synthetic HeapContinuation
- hc = new HeapContinuation(7);
+ hc = new HeapContinuation(3, // 3 stack elements
+ Nil.NIL, // previous continuation
+ env, // environment
+ 20); // saved IP
// Stack elements
hc.setIndex(0, Fixnum.get(1));
hc.setIndex(1, Fixnum.get(2));
hc.setIndex(2, Fixnum.get(3));
- hc.setIndex(3, Fixnum.get(20)); // instruction pointer
- hc.setIndex(4, Fixnum.ZERO); // base pointer
- hc.setIndex(5, env); // environment
- hc.setIndex(6, Nil.NIL); // previous continuation
// Code:
// env 2 0 0; lde0 0; push; lde0 1; apply 1; ret; hlt; hlt; hlt; hlt; hlt;
// add everything already on the stack to the value applied to the continuation, get the
// stuff in the environment and add it too, and return the sum.
// add; add; add; push; lde0 0; add; push; lde0 1; add; push; lde0 2; add; ret
byte inst[] = { (byte)0xca, 0x02, 0x00, 0x00, // env 1 0 0
0x69, 0x00, // lde0 0 ; value (fixnum)
0x01, // push
0x69, 0x01, // lde0 1 ; continuation
0x4c, 0x01, // apply 1
0x0d, // ret
0x14, // hlt
0x14, // hlt
0x14, // hlt
0x14, // hlt
0x14, // hlt
0x14, // hlt
0x14, // hlt
0x14, // hlt
0x15, // add ; continuation ip address
0x15, // add
0x15, // add
0x01, // push
0x69, 0x00, // lde0 0
0x15, // add
0x01, // push
0x69, 0x01, // lde0 1
0x15, // add
0x01, // push
0x69, 0x02, // lde0 2
0x15, // add
0x0d, // ret
};
VirtualMachine vm = new VirtualMachine(1024);
vm.load(inst, 0);
vm.setargc(2);
vm.push(Fixnum.get(7));
vm.push(hc);
vm.setAcc(Nil.NIL);
assertTrue(vm.runnable());
vm.run();
assertFalse(vm.runnable());
assertEquals(28, ((Fixnum)vm.getAcc()).fixnum);
}
}
|
dido/arcueid
|
6381d47224239f5f23d1566b487d4993183929ad
|
fromStackEnv accepts actual environment, does nothing if already HeapEnv
|
diff --git a/java/src/org/arcueidarc/nekoarc/HeapEnv.java b/java/src/org/arcueidarc/nekoarc/HeapEnv.java
index 2bdc58f..706a424 100644
--- a/java/src/org/arcueidarc/nekoarc/HeapEnv.java
+++ b/java/src/org/arcueidarc/nekoarc/HeapEnv.java
@@ -1,53 +1,54 @@
package org.arcueidarc.nekoarc;
import org.arcueidarc.nekoarc.types.ArcObject;
import org.arcueidarc.nekoarc.types.Fixnum;
import org.arcueidarc.nekoarc.types.Symbol;
import org.arcueidarc.nekoarc.types.Vector;
import org.arcueidarc.nekoarc.vm.VirtualMachine;
/** Heap environment */
public class HeapEnv extends Vector
{
public static final ArcObject TYPE = Symbol.intern("environment");
private ArcObject prev;
public HeapEnv(int size, ArcObject p)
{
super(size);
prev = p;
}
public ArcObject prevEnv()
{
return(prev);
}
public ArcObject getEnv(int index) throws NekoArcException
{
return(this.index(index));
}
public ArcObject setEnv(int index, ArcObject value)
{
return(setIndex(index, value));
}
// Convert a stack-based environment si into a heap environment. Also affects any
// environments linked to it.
- public static HeapEnv fromStackEnv(VirtualMachine vm, int si)
+ public static ArcObject fromStackEnv(VirtualMachine vm, ArcObject sei)
{
+ if (sei instanceof HeapEnv || sei.is(Nil.NIL))
+ return(sei);
+ int si = (int)((Fixnum)sei).fixnum;
int start = (int)((Fixnum)vm.stackIndex(si)).fixnum;
int size = (int)((Fixnum)vm.stackIndex(si+1)).fixnum;
ArcObject penv = vm.stackIndex(si+2);
- // If we have a stack-based env as the previous, convert it into a heap env too
- if (penv instanceof Fixnum)
- penv = fromStackEnv(vm, (int)((Fixnum)penv).fixnum);
- // otherwise, penv must be either NIL or a heap env as well
+ // Convert previous env into a stack-based one too
+ penv = fromStackEnv(vm, penv);
HeapEnv nenv = new HeapEnv(size, penv);
// Copy stack env data to new env
for (int i=0; i<size; i++)
nenv.setEnv(i, vm.stackIndex(start + i));
return(nenv);
}
}
|
dido/arcueid
|
a0fee0f6f5e75436620ea63911dd0686f2829993
|
setSP accessor method added
|
diff --git a/java/src/org/arcueidarc/nekoarc/vm/VirtualMachine.java b/java/src/org/arcueidarc/nekoarc/vm/VirtualMachine.java
index fe15033..8cf0e0e 100644
--- a/java/src/org/arcueidarc/nekoarc/vm/VirtualMachine.java
+++ b/java/src/org/arcueidarc/nekoarc/vm/VirtualMachine.java
@@ -1,662 +1,674 @@
package org.arcueidarc.nekoarc.vm;
import org.arcueidarc.nekoarc.Continuation;
+// import org.arcueidarc.nekoarc.HeapContinuation;
import org.arcueidarc.nekoarc.HeapEnv;
import org.arcueidarc.nekoarc.NekoArcException;
import org.arcueidarc.nekoarc.Nil;
import org.arcueidarc.nekoarc.Unbound;
import org.arcueidarc.nekoarc.types.ArcObject;
import org.arcueidarc.nekoarc.types.Fixnum;
import org.arcueidarc.nekoarc.types.Symbol;
import org.arcueidarc.nekoarc.util.CallSync;
import org.arcueidarc.nekoarc.util.Callable;
import org.arcueidarc.nekoarc.util.ObjectMap;
import org.arcueidarc.nekoarc.vm.instruction.*;
public class VirtualMachine implements Callable
{
private int sp; // stack pointer
private int bp; // base pointer
private ArcObject env; // environment pointer
private ArcObject cont; // continuation pointer
private ArcObject[] stack; // stack
private final CallSync caller;
private int ip; // instruction pointer
private byte[] code;
private boolean runnable;
private ArcObject acc; // accumulator
private ArcObject[] literals;
private int argc; // argument counter for current function
private static final INVALID NOINST = new INVALID();
private static final Instruction[] jmptbl = {
new NOP(), // 0x00
new PUSH(), // 0x01
new POP(), // 0x02
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
new RET(), // 0x0d
NOINST,
NOINST,
NOINST,
new NO(), // 0x11
new TRUE(), // 0x12
new NIL(), // 0x13
new HLT(), // 0x14
new ADD(), // 0x15
new SUB(), // 0x16
new MUL(), // 0x17
new DIV(), // 0x18
new CONS(), // 0x19
new CAR(), // 0x1a
new CDR(), // 0x1b
new SCAR(), // 0x1c
new SCDR(), // 0x1d
NOINST,
new IS(), // 0x1f
NOINST,
NOINST,
new DUP(), // 0x22
NOINST, // 0x23
new CONSR(), // 0x24
NOINST,
new DCAR(), // 0x26
new DCDR(), // 0x27
new SPL(), // 0x28
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
new LDL(), // 0x43
new LDI(), // 0x44
new LDG(), // 0x45
new STG(), // 0x46
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
new APPLY(), // 0x4c
new CLS(), // 0x4d,
new JMP(), // 0x4e
new JT(), // 0x4f
new JF(), // 0x50
new JBND(), // 0x51
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
new MENV(), // 0x65
NOINST,
NOINST,
NOINST,
new LDE0(), // 0x69
new STE0(), // 0x6a
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
new LDE(), // 0x87
new STE(), // 0x88
new CONT(), // 0x89
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
new ENV(), // 0xca
new ENVR(), // 0xcb
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
NOINST,
};
private ObjectMap<Symbol, ArcObject> genv = new ObjectMap<Symbol, ArcObject>();
public VirtualMachine(int stacksize)
{
sp = bp = 0;
stack = new ArcObject[stacksize];
ip = 0;
code = null;
runnable = true;
env = Nil.NIL;
cont = Nil.NIL;
setAcc(Nil.NIL);
caller = new CallSync();
}
public void load(final byte[] instructions, int ip, final ArcObject[] literals)
{
this.code = instructions;
this.literals = literals;
this.ip = ip;
}
public void load(final byte[] instructions, int ip)
{
load(instructions, ip, null);
}
public void halt()
{
runnable = false;
}
public void nextI()
{
ip++;
}
/**
* Attempt to garbage collect the stack, after Richard A. Kelsey, "Tail Recursive Stack Disciplines for an Interpreter"
* Basically, the only things on the stack that are garbage collected are environments and continuations.
* The algorithm here works by copying all environments and continuations from the stack to the heap. When that's done it will move the stack pointer
* to the top of the stack.
* 1. Start with the environment register. Move that environment and all of its children to the heap.
* 2. Continue with the continuation register. Copy the current continuation into the heap.
* 3. Compact the stack by moving the remainder of the non-stack/non-continuation elements to the heap.
*/
private void stackgc()
{
int stackbottom = -1;
if (env instanceof Fixnum) {
int si = (int)((Fixnum)env).fixnum;
stackbottom = (int)((Fixnum)stackIndex(si)).fixnum;
env = HeapEnv.fromStackEnv(this, si);
}
if (cont instanceof Fixnum) {
-// // Try to move the current continuation on the stack to the heap
-// Continuation nc = Continuation.fromStackCont(this, (Fixnum)cont);
-// cont = nc;
+ // If the current continuation is on the stack move it to the heap
+// ArcObject nc = HeapContinuation.fromStackCont(this, (Fixnum)cont);
+// this.setCont(nc);
// stackbottom = 0;
- stackbottom = (int)((Fixnum)cont).fixnum + 1;
+// stackbottom = (int)((Fixnum)cont).fixnum + 1;
}
// Garbage collection failed to produce memory
if (stackbottom < 0 || stackbottom > stack.length || stackbottom == bp)
return;
// move what we can of the used portion of the stack to the bottom.
for (int i=0; i<sp - bp - 1; i++)
setStackIndex(stackbottom + i, stackIndex(bp + i));
sp = stackbottom + (sp - bp - 1);
bp = stackbottom;
}
public void push(ArcObject obj)
{
for (;;) {
try {
stack[sp++] = obj;
return;
} catch (ArrayIndexOutOfBoundsException e) {
// We can try to garbage collect the stack
stackgc();
if (sp >= stack.length)
throw new NekoArcException("stack overflow");
}
}
}
public ArcObject pop()
{
return(stack[--sp]);
}
public void run()
throws NekoArcException
{
while (runnable) {
jmptbl[(int)code[ip++] & 0xff].invoke(this);
}
}
// Four-byte instruction arguments (most everything else). Little endian.
public int instArg()
{
long val = 0;
int data;
for (int i=0; i<4; i++) {
data = (((int)code[ip++]) & 0xff);
val |= data << i*8;
}
return((int)((val << 1) >> 1));
}
// one-byte instruction arguments (LDE/STE/ENV, etc.)
public byte smallInstArg()
{
return(code[ip++]);
}
public ArcObject getAcc()
{
return acc;
}
public void setAcc(ArcObject acc)
{
this.acc = acc;
}
public boolean runnable()
{
return(this.runnable);
}
+ public boolean setrunnable(boolean runstate)
+ {
+ this.runnable = runstate;
+ return(runstate);
+ }
+
public ArcObject literal(int offset)
{
return(literals[offset]);
}
public int getIP()
{
return ip;
}
public void setIP(int ip)
{
this.ip = ip;
}
public int getSP()
{
return(sp);
}
+ public void setSP(int sp)
+ {
+ this.sp = sp;
+ }
+
// add or replace a global binding
public ArcObject bind(Symbol sym, ArcObject binding)
{
genv.put(sym, binding);
return(binding);
}
public ArcObject value(Symbol sym)
{
if (!genv.containsKey(sym))
throw new NekoArcException("Unbound symbol " + sym);
return(genv.get(sym));
}
public int argc()
{
return(argc);
}
public int setargc(int ac)
{
return(argc = ac);
}
public void argcheck(int minarg, int maxarg)
{
if (argc() < minarg)
throw new NekoArcException("too few arguments, at least " + minarg + " required, " + argc() + " passed");
if (maxarg >= 0 && argc() > maxarg)
throw new NekoArcException("too many arguments, at most " + maxarg + " allowed, " + argc() + " passed");
}
public void argcheck(int arg)
{
argcheck(arg, arg);
}
/* Create an environment. If there is enough space on the stack, that environment will be there,
* if not, it will be created in the heap. */
public void mkenv(int prevsize, int extrasize)
{
if (sp + extrasize + 3 > stack.length) {
mkheapenv(prevsize, extrasize);
return;
}
// If there is enough space on the stack, create the environment there.
// Add the extra environment entries
for (int i=0; i<extrasize; i++)
push(Unbound.UNBOUND);
int count = prevsize + extrasize;
int envstart = sp - count;
/* Stack environments are basically Fixnum pointers into the stack. */
int envptr = sp;
push(Fixnum.get(envstart)); // envptr
push(Fixnum.get(count)); // envptr + 1
push(env); // envptr + 2
env = Fixnum.get(envptr);
bp = sp;
}
private void mkheapenv(int prevsize, int extrasize)
{
// First, convert the parent environment to a heap environment if it is not already one
if (env instanceof Fixnum)
env = HeapEnv.fromStackEnv(this, (int)((Fixnum)env).fixnum);
int envstart = sp - prevsize;
// Create new heap environment and copy the environment values from the stack into it
HeapEnv nenv = new HeapEnv(prevsize + extrasize, env);
for (int i=0; i<prevsize; i++)
nenv.setEnv(i, stackIndex(envstart + i));
// Fill in extra environment entries with UNBOUND
for (int i=prevsize; i<prevsize+extrasize; i++)
nenv.setEnv(i, Unbound.UNBOUND);
bp = sp;
env = nenv;
}
/** move current environment to heap if needed */
public ArcObject heapenv()
{
if (env instanceof Fixnum)
env = HeapEnv.fromStackEnv(this, (int)((Fixnum)env).fixnum);
return(env);
}
private ArcObject findenv(int depth)
{
ArcObject cenv = env;
while (depth-- > 0 && !cenv.is(Nil.NIL)) {
if (cenv instanceof Fixnum) {
int index = (int)((Fixnum)cenv).fixnum;
cenv = stackIndex(index+2);
} else {
HeapEnv e = (HeapEnv)cenv;
cenv = e.prevEnv();
}
}
return(cenv);
}
public ArcObject getenv(int depth, int index)
{
ArcObject cenv = findenv(depth);
if (cenv == Nil.NIL)
throw new NekoArcException("environment depth exceeded");
if (cenv instanceof Fixnum) {
int si = (int)((Fixnum)cenv).fixnum;
int start = (int)((Fixnum)stackIndex(si)).fixnum;
int size = (int)((Fixnum)stackIndex(si+1)).fixnum;
if (index > size)
throw new NekoArcException("stack environment index exceeded");
return(stackIndex(start+index));
}
return(((HeapEnv)cenv).getEnv(index));
}
public ArcObject setenv(int depth, int index, ArcObject value)
{
ArcObject cenv = findenv(depth);
if (cenv == Nil.NIL)
throw new NekoArcException("environment depth exceeded");
if (cenv instanceof Fixnum) {
int si = (int)((Fixnum)cenv).fixnum;
int start = (int)((Fixnum)stackIndex(si)).fixnum;
int size = (int)((Fixnum)stackIndex(si+1)).fixnum;
if (index > size)
throw new NekoArcException("stack environment index exceeded");
return(setStackIndex(start+index, value));
}
return(((HeapEnv)cenv).setEnv(index,value));
}
public ArcObject stackIndex(int index)
{
return(stack[index]);
}
public ArcObject setStackIndex(int index, ArcObject value)
{
return(stack[index] = value);
}
// Make a continuation on the stack. The new continuation is saved in the continuation register.
public void makecont(int ipoffset)
{
if (sp + 4 > stack.length) {
// Try to do stack gc first. If it fails, nothing for it
stackgc();
if (sp + 4 > stack.length)
throw new NekoArcException("stack overflow while creating continuation");
}
int newip = ip + ipoffset;
push(Fixnum.get(newip));
push(Fixnum.get(bp));
push(env);
push(cont);
cont = Fixnum.get(sp);
}
public void restorecont()
{
restorecont(this);
}
// Restore continuation
public void restorecont(Callable caller)
{
if (cont instanceof Fixnum) {
sp = (int)((Fixnum)cont).fixnum;
cont = pop();
setenvreg(pop());
setBP((int)((Fixnum)pop()).fixnum);
setIP((int)((Fixnum)pop()).fixnum);
} else if (cont instanceof Continuation) {
((Continuation)cont).restore(this, caller);
} else if (cont.is(Nil.NIL)) {
// If we have no continuation, that was an attempt to return from the topmost
// level and we should halt the machine.
halt();
} else {
throw new NekoArcException("invalid continuation");
}
}
public void setenvreg(ArcObject env)
{
this.env = env;
}
public int getBP()
{
return bp;
}
public void setBP(int bp)
{
this.bp = bp;
}
public ArcObject getCont()
{
return cont;
}
public void setCont(ArcObject cont)
{
this.cont = cont;
}
@Override
public CallSync sync()
{
return(caller);
}
}
|
dido/arcueid
|
e6abf14568a54bf89b496774ea3dc5af38bd0f8d
|
empty test for ccc for now
|
diff --git a/java/test/org/arcueidarc/nekoarc/functions/CCCtest.java b/java/test/org/arcueidarc/nekoarc/functions/CCCtest.java
new file mode 100644
index 0000000..b1a2d5d
--- /dev/null
+++ b/java/test/org/arcueidarc/nekoarc/functions/CCCtest.java
@@ -0,0 +1,15 @@
+package org.arcueidarc.nekoarc.functions;
+
+import static org.junit.Assert.*;
+
+import org.junit.Test;
+
+public class CCCtest
+{
+ @Test
+ public void test()
+ {
+ fail("Not yet implemented");
+ }
+
+}
|
dido/arcueid
|
23eebfb0f0a9aa417ba8d6c2b90994d547b06da4
|
implementation of call/cc
|
diff --git a/java/src/org/arcueidarc/nekoarc/functions/CCC.java b/java/src/org/arcueidarc/nekoarc/functions/CCC.java
index 26516bd..ae8fc14 100644
--- a/java/src/org/arcueidarc/nekoarc/functions/CCC.java
+++ b/java/src/org/arcueidarc/nekoarc/functions/CCC.java
@@ -1,20 +1,27 @@
package org.arcueidarc.nekoarc.functions;
+import org.arcueidarc.nekoarc.HeapContinuation;
import org.arcueidarc.nekoarc.InvokeThread;
+import org.arcueidarc.nekoarc.NekoArcException;
import org.arcueidarc.nekoarc.types.ArcObject;
+import org.arcueidarc.nekoarc.types.Fixnum;
public class CCC extends Builtin
{
protected CCC()
{
super("ccc", 1);
}
@Override
- public ArcObject invoke(InvokeThread vm)
+ public ArcObject invoke(InvokeThread thr)
{
- // XXX - todo
- return null;
+ ArcObject continuation = thr.vm.getCont();
+ if (continuation instanceof Fixnum)
+ continuation = HeapContinuation.fromStackCont(thr.vm, continuation);
+ if (!(continuation instanceof HeapContinuation))
+ throw new NekoArcException("Invalid continuation type " + continuation.type().toString());
+ return(thr.apply(thr.getenv(0, 0), continuation));
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.