Apache2 & eruby, as 10 years ago - html

Why can't I use eruby without Rails ? I don't like Rails, but it seems eruby has not been used without Rails for a decade (If I refer on the dates of the lasts questions about eruby on Stack Overflow).
Here are the lines that I added to my Apache configuration to handle .erb scripts :
AddHandler application/x-httpd-erb .erb
Action application/x-httpd-erb "/cgi-bin/erb-cgi.rb"
When I try to load a simple test page (located on myserver.fr/test.erb), I get the following error :
The requested URL /cgi-bin/erb-cgi.rb/test.erb was not found on this server.
It seems like Apache try to open "/cgi-bin/erb-cgi.rb/test.erb" instead of running /cgi-bin/erb-cgi.rb with test.erb as a parameter (what should be the normal behavior of the Action directive)
I don't detail here the /cgi-bin/erb-cgi.rb script, the server doesn't even try to open it.
It was working for the whole world 10 year ago, I don't think I'm doing something wrong... Am I ? (Of course I am)
And yes, I'm french, so there is a nonzero probability that my English is bad. Thanks for your help!

Not exactly what you asked for, but if you want easy templating in Ruby without Rails, you may want to have a look at Sinatra, a very lightweight framework build in Ruby.
Sinatra can be run in a single command, manages routes and templates, and that's about it.

Related

Alternatives to CGI.pm for header() and param()?

I've been an avid user of CGI.pm since the previous millennium so I was a bit surprised when it disappeared from my old Ubuntu server when I upgraded it recently. My short-term fix was sudo cpan install CGI, but a quick web search to find out why it was missing in the first place revealed CGI::Alternatives which explains why it has gone and offers some suggestions for alternatives. For my purposes, HTML::Tiny looks best for replacing my programmatic HTML generation, but Alternatives is strangely silent on the subject of HTTP headers and CGI parameters.
I broadened by search and found lighter alternatives to CGI.pm on perlmonks where one response suggests CGI::Simple, but the recommendation is less than whole-hearted - "its not quite as up to date as CGI.pm".
So is CGI::Simple the way to go, or is there a better alternative?
Please don't spend time suggesting "rewrite everything using framework XXX". I really don't have the time or energy for that. I'm happy to replace all my HTML generation with HTML::Tiny, so I'm looking for something with a similar (or lower!) amount of rework to replace header() and param().
You're missing the point if you're looking for an alternative that provides header and param.
The argument for the removal of CGI.pm from core (but not from CPAN) is that you shouldn't have to deal with CGI yourself; you should be using a framework that handles this for you.
If you don't agree with this — if you're looking for an equivalent to header and param — go ahead and keep using CGI.pm.
If you do agree, CGI::Simple is no better than CGI.pm.
As others have said, there's no reason not to use CGI together with HTML::Tiny. So that's the answer to your question. For the last five years that I was using CGI, my programs all started something like:
use CGI qw[param header];
which is the approach you're talking about here.
If you wait a year or two, the plan is for the HTML generation functions to be removed from the main module, so your problems will all go away at that point.
But that's not what I'd do in your situation. I'd switch to using PSGI and Plack. You said that you don't want anyone to suggest a new framework, so I'm not going to do that. Plack isn't a framework, it's a toolbox for writing PSGI applications. Certainly, I'd use a framework like Dancer, but you don't have to. You can happily use Plack without any of the frameworks built on top of it.
You'll still get most of the advantages of PSGI. You'll be able to deploy your applications in any way you like. You'll have access to all the awesome Plack middleware. Testing your program will be far easier.
When you're using "raw" Plack, the equivalent of CGI::param is Plack::Request::parameters and the equivalent of CGI::header is Plack::Response::headers.
So there are three answers to your question.
Carry on using CGI.pm. Just stop using the HTML generation functions and replace them with HTML::Tiny
Use raw PSGI/Plack and bring your web development into the 21st century
Use one of Perl's many great web frameworks.
Unfortunately, you don't seem to like any of those answers.
The issue with CGI.pm is not that it's going away, merely that it will no longer be distributed as part of the core Perl distribution. However that doesn't mean you have to install from CPAN. On your Ubuntu system you can just do:
sudo apt-get install libcgi-pm-perl
and you'll be off and running with the same old CGI you know and love :-)
The correct answer to my question is that use CGI::Simple is better than use CGI qw(header param) because it loads faster.
Answers along the lines of "Use Plack, it's the future of Perl for websites" weren't helpful to me because I didn't have time to learn a new programming paradigm or to discover how to reconfigure my web server to make it work, no matter how insistent the Plack Evangelists were that I was wrong in what I was trying to do.
I've now had a bit of time to wade through the links to documentation and presentation slides I was offered and I can see what they were getting at, but one failing in what I've read so far is the lack of a concise end-to-end working example to help get my head around things ... so here's what I knocked together to get me started (and, no, I haven't finished yet!). I hope that others beginning the journey from CGI to PSGI will find this useful to help get them underway...
First you need to install Plack. I'm running an Ubuntu 14.04 installation so it was simply a matter of running sudo apt-get install libplack-perl. The generic way is to install Task::Plack from CPAN.
Next you need to know where your cgi-bin directory is located. You ought to know already if you're a CGI die-hard! Since I'm running Apache mine is defined in /etc/apache2/conf-available/serve-cgi-bin.conf by ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/.
Now for the magic. We're going to create a CGI script that runs a PSGI app, handing it data from the CGI environment. This is good for experimentation and testing but NOT for deployment, as you don't get any of the speed benefit that PSGI can give you (for that you need something like Plack::Handler::Apache2, Plack::Handler::FCGI or mod_psgi in Apache, or a dedicated PSGI server such as Starman or Starlet, or one of the other handlers mentioned on PlackPerl.org). Create /usr/lib/cgi-bin/psgi-cgi.pl with the following contents and make it executable:-
#!/usr/bin/perl
use Plack::Util;
use Plack::Handler::CGI;
my $app = Plack::Util::load_psgi($ENV{PATH_TRANSLATED});
Plack::Handler::CGI->new->run($app);
Next we need to tell Apache to pass PSGI app files to this handler. I did this by creating /etc/apache2/conf-available/psgi-cgi.conf containing:-
Action psgi-cgi /cgi-bin/psgi-cgi.pl
AddHandler psgi-cgi .psgi
then loaded it into my Apache server by running sudo a2enconf psgi-cgi and sudo service apache2 reload. Basically you need to get these lines into your httpd.conf file and restart the server.
Finally, my first PSGI script, which I created in my server's DocumentRoot as /var/www/html/hello.psgi:-
use Plack::Request;
my $app = sub {
my $env = shift;
my $req = Plack::Request->new($env);
my $par = $req->parameters;
return [
200,
[ 'Content-Type', 'text/plain' ],
[ "Hello world!\n",
map("$_ = ".join(", ", $par->get_all($_))."\n", sort keys %$par),
]
];
};
The application is a coderef which returns a 3-element arrayref: the first is the HTTP status code, the second is the name,value pairs for the HTTP header, the third is the body of the response (which could be generated using HTML::Tiny for a web page). The first 2 elements answer the question of what you need instead of the CGI::header function - nothing! (though for more complex handling you'll need Plack::Response::headers). The example also shows how to replace CGI::param - use Plack::Request::parameters, which returns a Hash::MultiValue object containing the values of URL (GET) and BODY (POST) parameters, including the ones with multiple values.
Finally, a test:-
$ wget -q -O- 'http://localhost/hello.psgi?a=1&a=2&a=3&b=1&b=4'
Hello world!
a = 1, 2, 3
b = 1, 4
I hope this is useful to other CGI die-hards in taking their first steps towards PSGI proficiency, and I hope the Plack Evangelists will acknowledge that it takes a lot of reading and comprehension to get even this far.
CGI::Minimal would a good option, it is much lighter than CGI & CGI::Simple, but it lacks advanced methods like CGI & CGI::Simple

Is it possible to create a web site aside copying and pasting it on every page? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I'm building my own blog and I would have lots of articles, so, copying and pasting the head every time, or an aside, the footer or some repeated parts of the blog would be stupid.
So, I'm looking a way to do it in an easy way. I heared about templating (but don't know what it is) and found this answer: Is it possible to create a web site header without copying and pasting it on every page? but it seems that is not what I'm looking for.
I heared about HAML and Markdown (HTML Preprocessors) and don't know if they are used to do what I need.
The solution I want to find is something like #import in Sass.
I have an #import "head.scss"; and in the compiled file I hadn't repeated manualy the (in this case an "imported module" head.scss)
I might say I'm learning to develop my static blog with Jekyll, just because I want to learn to use this technology, and second I know how to use WordPress, Joomla and learning a new thing would be interesting for me but I don't want to learn PHP so I think a templating language will be easier for this project
If you want to use Jekyll, you can use includes to avoid repeating code.
If You are looking easier ways for managing posts and front matter You should look into Jekyll Bash UI or Octopress.
If You want to learn more about Jekyll and its templating system, I'd recommend You to read the Jeyll.tips web page. It contains well formatted and easy to read how-tos, and also covers advanced topics like data files and collections.
Jekyll Bash UI (requires Bash)
Creating a new post is quite easy process, just this on the command line:
jcli.sh new
Octopress
Octopress uses rake utility which makes using Jekyll easier.
For creating a post You just have to call this:
rake new_post["My new post with Octopress"].
After this You can call rake generate to generate the page or rake preview to run the webserver at localhost on port 4000, so You can preview the changes.
The answer is yes it's possible.
In order for a scss file to work you have to make sure the .scss file (or sass file) is converted to css first. (you can look up the many sass tutorials online. for that, just look for converting sass or scss files into css there are even little simple applications for that like scout) By the way, with less you can do the same thing for css files as with sass in terms of importing.
For html files there are templating engines like you said. You can compare popular ones like moustache, dust.js and handlebars just to name a few.
With these you can import snippets of html code inside your file (so you do not have to repeat code).
In programming languages like JavaScript and php you can also do the same thing.
in PHP you can use for example the include() or require() function to import other bits of code from other files into your current file. And in languages like JavaScript you can even use something like angular for example to create simple custom directives to achieve the same goal.
Pretty much every server side language I've worked with has shared views in some manner or another.
asp.net webforms has master pages, asp.net mvc has shared views, coldfusion has cfinclude, RoR has partials, PHP has shared layout. I don't know about straight up HTML, but when utilizing a server side language this is definitely possible.
I would suggest using a content management system, like WordPress (https://wordpress.com/) , Joomla (http://www.joomla.org/), or Drupal (https://www.drupal.org/). You create a template one time and load it into the CMS. You can then create as many pages as you need without having copy and paste the template. You can also add in different elements as needed. This makes managing a blog much easier.
If you dead set on doing it one page at a time, I would suggest using PHP to pull in the header. Here is a good article to get you started, Creating a PHP header/footer . However, you'll still need to copy and paste a template file to create a new page.

How can I easily save the HTML pages of my Rails app, to give to Designer?

I am working on a Rails app, and a designer is designing the raw HTML pages separately. Its tough to get his environment set up to use the application directly, so I would like to be able to somehow "store" the HTML of all of the pages that my application generates, to a directory somewhere to that I can pass the curent version off to the designer.
Does anyone know of a gem or rake task that would help me do something likee this?
I am also open to other suggestions for working in parallel with designers who don't know rails.
Thanks
Edit
I guess an amendment to my question, would be, does anyone also know of ways of generating the list of page links to feed to wget, other than going through them by hand
Edit 2
Just thinking out loud... to generate every possible page in an app, you'd need to call every action in every controller. So i'd need a program to find which controllers exist in all of my app/gems/plugins, and then find all of the public methods in them.. Or.. maybe I could just use the actions that are routable from the list of routes
Then, you might want to filter out the actions that didn't render html
Then you might want to filter out destructive actions (unless this program ran in a test environment, and rebuilt the system every time).
Then as many actions depend on the parameters that are supplied, you'd need to have control over which parameters are sent to each action...
Then you'd also have to be able to send session cookies to log in
what else..
wget -m http://somewhere.com
This command will fetch all the files / pages from http://somewhere.com and download them to a local directory, to form a local "mirror."
-m
--mirror
Turn on options suitable for mirroring. This option turns
on recursion and time-stamping, sets infinite recursion depth and
keeps FTP directory listings. It is currently equivalent to -r -N -l
inf --no-remove-listing.
Note: I don't believe Mac OS X ships with wget. If you are using a Mac, I'd suggest installing Homebrew and then running brew install wget.
Read more: man wget

CGI language choice

Ok, I've asked a few related questions here and only ended up with more questions and I realized now it's because I don't have enough background info. So I'll make it more generic:
I need to make a simple web application. Static HTML/JQuery pages will send AJAX POST requests to some server side code, which will:
Read the POST variables passed in
Run some very simple logic
Hit a MySQL database for simple CRUD ops
Return a plain string of data to be consumed by the javascript on the page
I was assuming Ruby was a good choice for this as everyone is raving about how well it's designed, and I've been playing with it - not RoR, just Ruby for simple scripting tasks - and I kind of like it.
My question is, I'm hopelessly confused by the trillion helper libraries and frameworks out there. I don't know what these are and therefore if I need any/all of them: Rack, Sinatra, Camping, mod_ruby, FastCGI, etc.
Would it be easier to just learn PHP and us that? Or can I get away with just dropping my .rb files into the cgi-bin folder(I'm using Apache for hosting) and use the ruby cgi library to get my variables?
EDIT: As far as Rails, I'm just assuming that it's overkill for what I want but I might be wrong. I looked at it, and it seemed cool for generating data based web sites quickly, but that's not what I'm trying to do. I don't want any forms pages for the user. I don't want them entering data or viewing records. I don't even want to return any HTML. I just want a ruby script to sit on the server, get passed a few variables in a post request, and return a JSON string in response. I will need some basic cookie/session/state managment
This is a really easy thing to do in C# and ASP.NET with webservices, but it seems very confusing with the open source technologies.
You don't want to use any feature from a fully blown framework so don't use one. Less code = less bugs = less security nightmares.
CGI
CGI has some performance drawbacks in comparison to other methods, but is still (in my opinion) the simplest and easiest to use one. This is how you use the builtin cgi library:
require "cgi"
cgi= CGI.new
answer= evaluate(cgi.params)
cgi.out do
answer
end
rack
Another low tech easy to use variant would be rack. Rack is an abstraction layer which works for many webserver interfaces (cgi, fastcgi, webrick, …). It's simplicity can be compared to the one of only using cgi. Put the following into a file wich ends with .ru into your cgi directory.
#!/usr/bin/rackup
require "rack/request"
run (lambda do |env|
request= Rack::Request(env)
anwser= evaluate(request.params)
return [200, {}, answer]
end)
This does not seem very different from cgi, but it gives you much more possibilities. If youst execute this file on your local machine rackup will start the webrick webserver. This webserver will deliver the webpages you described in your .ru file.
Other interfaces
fast-cgi
fast-cgi works almost like CGI. The difference is, in CGI your script get's started for every request it has to work on. With fast-cgi, your script only starts once for all requests. There is a library available to write fast-cgi script in ruby.
mod_ruby
mod_ruby is a builtin ruby interpreter for apache. It works analog to mod_php in apache.
mongrel
mongrel is a standalone webserver for ruby applications. This is a simple hello world example with it.
require 'mongrel'
class SimpleHandler < Mongrel::HttpHandler
def process(request, response)
response.start(200) do |head,out|
head["Content-Type"] = "text/plain"
out.write("hello world!\n")
end
end
end
h = Mongrel::HttpServer.new("0.0.0.0", "3000")
h.register("/hello", SimpleHandler.new)
h.run.join
Mongrel is often used for rails and other ruby frameworks. Most people use an apache or something else on port 80. This webserver than distributes the requests to several mongrel servers running on other ports. I think this is totaly overkill for your needs.
phusion passenger
passenger is also called mod_rails or mod_rack. It is a module for apache and nginx to host rails and rack applications. According to their websites rails with passenger uses 1/3 less ram than rails alone. If you write your software for rack, you could make it a little faster by using passenger, instead of cgi or fast-cgi.
Use jQuery and PHP.
Both technologies are well documented, and you should be able to get an application up and running in a matter of hours. You sound like you know a thing or two - talking about CRUD operations and so on - so I won't bore you with examples. And as far as JSON goes, there are probably a million PHP libraries out there, for outputting JSON objects.
Sinatra is very simple to learn and use. It's also easy to deploy with the use of Phusion Passenger (which is like mod_php for ruby frameworks like Rails and Sinatra). Instructions here: http://blog.squarefour.net/2009/03/06/deploying-sinatra-on-passenger/
If you find that you need more than what Sinatra will give you, I recommend Rails. Setting up that with Passenger is even easier since hardly any configuration is required. (see modrails.com).
PHP is very easy to use because it's designed specifically for this sort of thing. Want to read POST variables? They're in $_POST. Want to query MySQL? mysql_query("SELECT `something` FROM `table`");. And if you ever need help, Google searches for "php what_you_need_to_do" almost always return results on php.net, which is very helpful.
And for what you're doing, you don't need any additional frameworks.
I am curious about what I perceive to be your resistance to trying Rails. You say that you want "to spend more time on the scripting itself and less on configuration", and yet you seem to dismiss Rails out of hand. Rails is all about convention over configuration. If you take the time to learn how Rails does things, you can get an incredible amount of functionality "for free" just by following the conventions of the framework.
If you want to make a simple web app, Rails is really a very painless and good way to start. You can use a sqlite database and not even mess with MySQL (won't scale, but for learning or simple apps it's fine). It's true that there are simpler frameworks, but since you seem new to web programming, I'd recommend that you start with what will get you the most support in terms of documentation and knowledgeable folks. Follow the old adage: Get it working first, then optimize later.
The only sticking point I can see is the Apache integration... The consensus on Rails deployment these days seems to be focused on using lightweight httpds in place of Apache. There is a mod_fcgid which seems to be the best way to do it with Apache (mod_ruby is deprecated, buggy and slow, last I read) if you can do custom mods. Or there's Phusion Passenger, which seems to be the latest and greatest way to do it. Running Rails in a standard CGI environment will yield awful performance (but that goes for any CGI framework, really) due to the overhead of executing the interpreter + framework for every request. You'll get much better performance if you go with something that keeps the interpreter + framework in memory.
I personally like Django. I had a problem with Ruby on Rails where I just got overwhelmed by everything when I just wanted to do something simple, which it sounds like you want to do (since you said ROR feels like overkill). The cool thing I found with Django is that if you WANT everything, then you can get everything by plugging it in...but if you want less then you just don't plug in that technology and it's that much more lightweight.
Take for example "views". Django, like ROR, uses MVC. But if you just want to return a string of data and don't need the view, then you don't need to plug in the view. But if later on you decide that it will be more organized in a view then you can easily plug it in at that time.
Here's their website: http://www.djangoproject.com/

With Rails, where should I put html snippets? I don't want partials but I want them reloaded during development

Being lazy (and liking DRY code), I'm the kind of guy who's going to write a few little wrappers for recurring HTML markup. Those provided by Rails are good already, but sometimes I have something a little more specific that I know I'm going to repeat over and over.
In some situations a partial can be the solution, but sometimes I'm just going to call the snippet way too often to justify the overhead of using partials.
Right now I create a helpers/html_helper.rb file and stick them in there. The problem is that helpers are not reloaded dynamically per request during development. So each time I tweak my snippet or the code around it, I have to kill the server and restart it.
Granted, it's just a 5 seconds process, but I love Rails' convenience of just developing and then refreshing the browser. So I'd love to have that for my markup snippets as well.
Note: Just sticking 'unloadable' inside the helper module doesn't work.
Good question! This is a technique I should abuse more frequently.
#I go in environment.db (presumably it will work in one of the per-environment files, too.)
Dependencies.explicitly_unloadable_constants << 'NameOfHelperToReloadHere'
That array starts out empty, incidentally, at least in my install. (Checked via console.)
I tested this locally and it works for me, at least on Rails 2.0.2. Major credit for the solution belongs to this gentleman.
If you stick them in application_helper.rb they'll be loaded every time and be available for all of your views. This is loaded every time in development mode (or at least I haven't encountered any issues).
I typically will create little helpers that I use throughout the site (sortable table headers for instance) that use the same logic.
This should reload ALL helpers on every request (assuming you've stuck to the default naming conventions)
#Put this in config/environments/development.rb
ActiveSupport::Dependencies.explicitly_unloadable_constants.concat(Dir.glob("#{RAILS_ROOT}/app/helpers/**/*.rb").map {|file| File.basename(file, '.rb').camelize})
Or if you are using an older version of Rails (2.0.2 or earlier I think)
#Put this in config/environments/development.rb
Dependencies.explicitly_unloadable_constants.concat(Dir.glob("#{RAILS_ROOT}/app/helpers/**/*.rb").map {|file| File.basename(file, '.rb').camelize})
Works for me in RoR 2.1.1
Update: modified top snippet to include 'ActiveSupport::', must have copied / pasted incorrectly from my code.
It's not a real solution but you could use tests (TestUnit, RSpec or whatever) to make sure your helpers work as expected. That way, you wouldn't rely on automatic reloading of your helpers so much.