override redirect url after submit with <delete button> in Hobo rails - hobo

where is code for redirect .. i am using hobo 0.8 version with rails 2.x
'<pre>
'< 'def tag = "trash" attrs ="no-redirect" >
< delete-button with="&this" after-submit="#{redirect_uri}" title = " #{tooltip}"
label="Erase !" class="nav-button" / >
</ def>'
</pre>

redirects in Rails & Hobo are done in the controller, especially in 5 year old versions of Hobo. Hobo 2.0 has other ways of doing this, but in Hobo 0.8, this is your only option:
def destroy
hobo_destroy
redirect_to redirect_url
end

Related

Prevent jekyll from cleaning up generated JSON file?

I've written a simple plugin that generates a small JSON file
module Jekyll
require 'pathname'
require 'json'
class SearchFileGenerator < Generator
safe true
def generate(site)
output = [{"title" => "Test"}]
path = Pathname.new(site.dest) + "search.json"
FileUtils.mkdir_p(File.dirname(path))
File.open(path, 'w') do |f|
f.write("---\nlayout: null\n---\n")
f.write(output.to_json)
end
# 1/0
end
end
end
But the generated JSON file gets deleted every time Jekyll runs to completion. If I uncomment the division by zero line and cause it to error out, I can see that the search.json file is being generated, but it's getting subsequently deleted. How do I prevent this?
I found the following issue, which suggested adding the file to keep_files: https://github.com/jekyll/jekyll/issues/5162 which worked:
The new code seems to avoid search.json from getting deleted:
module Jekyll
require 'pathname'
require 'json'
class SearchFileGenerator < Generator
safe true
def generate(site)
output = [{"title" => "Test"}]
path = Pathname.new(site.dest) + "search.json"
FileUtils.mkdir_p(File.dirname(path))
File.open(path, 'w') do |f|
f.write("---\nlayout: null\n---\n")
f.write(output.to_json)
end
site.keep_files << "search.json"
end
end
end
Add your new page to site.pages :
module Jekyll
class SearchFileGenerator < Generator
def generate(site)
#site = site
search = PageWithoutAFile.new(#site, site.source, "/", "search.json")
search.data["layout"] = nil
search.content = [{"title" => "Test 32"}].to_json
#site.pages << search
end
end
end
Inspired by jekyll-feed code.

How to enable automatic code reloading in Rails

Is there a way to do 'hot code reloading' with a Rails application in the development environment?
For example: I'm working on a Rails application, I add a few lines of css in a stylesheet, I look at the browser to see the modified styling. As of right now I have to refresh the page with cmd-r or by clicking the refresh button.
Is there a way to get the page to reload automatically when changes are made?
This works nicely in the Phoenix web framework (and I'm sure Phoenix isn't the only framework in this feature). How could a feature like this be enabled in Ruby on Rails?
I am using this setup reloads all assets, js, css, ruby files
in Gemfile
group :development, :test do
gem 'guard-livereload', '~> 2.5', require: false
end
group :development do
gem 'listen'
gem 'guard'
gem 'guard-zeus'
gem 'rack-livereload'
end
insert this in your development.rb
config.middleware.insert_after ActionDispatch::Static, Rack::LiveReload
i have this in my guard file
# A sample Guardfile
# More info at https://github.com/guard/guard#readme
## Uncomment and set this to only include directories you want to watch
# directories %w(app lib config test spec features) \
# .select{|d| Dir.exists?(d) ? d : UI.warning("Directory #{d} does not exist")}
## Note: if you are using the `directories` clause above and you are not
## watching the project directory ('.'), then you will want to move
## the Guardfile to a watched dir and symlink it back, e.g.
#
# $ mkdir config
# $ mv Guardfile config/
# $ ln -s config/Guardfile .
#
# and, you'll have to watch "config/Guardfile" instead of "Guardfile"
guard 'livereload' do
extensions = {
css: :css,
scss: :css,
sass: :css,
js: :js,
coffee: :js,
html: :html,
png: :png,
gif: :gif,
jpg: :jpg,
jpeg: :jpeg,
# less: :less, # uncomment if you want LESS stylesheets done in browser
}
rails_view_exts = %w(erb haml slim)
# file types LiveReload may optimize refresh for
compiled_exts = extensions.values.uniq
watch(%r{public/.+\.(#{compiled_exts * '|'})})
extensions.each do |ext, type|
watch(%r{
(?:app|vendor)
(?:/assets/\w+/(?<path>[^.]+) # path+base without extension
(?<ext>\.#{ext})) # matching extension (must be first encountered)
(?:\.\w+|$) # other extensions
}x) do |m|
path = m[1]
"/assets/#{path}.#{type}"
end
end
# file needing a full reload of the page anyway
watch(%r{app/views/.+\.(#{rails_view_exts * '|'})$})
watch(%r{app/helpers/.+\.rb})
watch(%r{config/locales/.+\.yml})
end
guard 'zeus' do
require 'ostruct'
rspec = OpenStruct.new
# rspec.spec_dir = 'spec'
# rspec.spec = ->(m) { "#{rspec.spec_dir}/#{m}_spec.rb" }
# rspec.spec_helper = "#{rspec.spec_dir}/spec_helper.rb"
# matchers
# rspec.spec_files = /^#{rspec.spec_dir}\/.+_spec\.rb$/
# Ruby apps
ruby = OpenStruct.new
ruby.lib_files = /^(lib\/.+)\.rb$/
# watch(rspec.spec_files)
# watch(rspec.spec_helper) { rspec.spec_dir }
# watch(ruby.lib_files) { |m| rspec.spec.call(m[1]) }
# Rails example
rails = OpenStruct.new
rails.app_files = /^app\/(.+)\.rb$/
rails.views_n_layouts = /^app\/(.+(?:\.erb|\.haml|\.slim))$/
rails.controllers = %r{^app/controllers/(.+)_controller\.rb$}
# watch(rails.app_files) { |m| rspec.spec.call(m[1]) }
# watch(rails.views_n_layouts) { |m| rspec.spec.call(m[1]) }
# watch(rails.controllers) do |m|
# [
# rspec.spec.call("routing/#{m[1]}_routing"),
# rspec.spec.call("controllers/#{m[1]}_controller"),
# rspec.spec.call("acceptance/#{m[1]}")
# ]
# end
end
I am using zeus instead of spring on this setup.
Run guard
Open localhost:3000 and you are good to go.
This should resolve your question, and have blazing reload times better than browserify.
I commented out guard looking at test directories if you want you can uncomment those lines if your are doing TDD.
CSS hot swapping and auto-reload when HTML/JS changes can be achieved with guard in combination with livereload: https://github.com/guard/guard-livereload
This gem would auto reload when you make changes to js elements(Not css or ruby files).
https://github.com/rmosolgo/react-rails-hot-loader
Never seen css hot code reloading in rails platform.

How to create a rails 4 offline webapp?

I'm trying to create an app with Rails 4 that should be usable without internet connection.
I've heard about html5 application cache and the rack-offline gem which is the approach I took.
Now, it seems that it's not working properly on Rails 4 since the /application.manifest only shows:
CACHE MANIFEST
# dd1ba6bba9339ef83f9c1225c70289dd6326d3caae01b0d52b502381030dc78f
404.html
422.html
500.html
NETWORK:
*
Also, I'm using assets precompile so the application.js, application.css and the image files has a fingerprint in their names, something like application-e8cc2fba8275c884c.js.
I made my own solution in a generate_appcahe_manifest.rake file and put it in /lib/tasks folder.
task :generate_appcache_file => ['deploy:precompile_assets', 'html5_manifest']
desc "Create html5 manifest.appcache"
task :html5_manifest => :environment do
puts 'Creating appcache manifest file...'
File.open("public/manifest.appcache", "w") do |f|
f.write("CACHE MANIFEST\n")
f.write("# Version #{Time.now.to_i}\n\n")
f.write("CACHE:\n")
assets = Dir.glob(File.join(Rails.root, 'public/assets/**/*'))
assets.each do |asset|
if File.extname(asset) != '.gz' && File.extname(asset) != '' && File.extname(asset) != '.json'
filename_path = /#{Rails.root.to_s}\/public\/(assets\/.*)/.match(File.absolute_path(asset))[1].to_s
# f.write("assets/#{File.basename(asset)}\n")
f.write(filename_path.concat("\n"))
end
end
f.write("\nNETWORK:\n")
f.write("*\n")
f.write("http://*\n")
f.write("https://*\n")
end
puts 'Done.'
end
namespace :deploy do
task :precompile_assets do
require 'fileutils'
if File.directory?("#{Rails.root.to_s}/public/assets")
FileUtils.rm_r "#{Rails.root.to_s}/public/assets"
end
puts 'Precompiling assets...'
puts `RAILS_ENV=production bundle exec rake assets:precompile`
puts 'Done.'
end
end
So when I run rake generate_appcache_file on the terminal, I got a /public/manifest.appcache file with the compiled assets like this:
CACHE MANIFEST
# Version 1409045103
CACHE:
assets/app/backgrounds/strips-05561384267a3286ab382c852f1e8b0d.jpg
assets/app/backgrounds/team-12e0fc5f670794c4eba3db117fba6746.jpg
assets/app-a7de6b02d1d39b783fe4e7ab7906ec95.css
assets/app-ae958853aa13f9011e35121cbe5b3cfe.js
NETWORK:
*
http://*
https://*
Finally, I call that file on my /app/views/layouts/app.html.erb file:
<!DOCTYPE html>
<html lang="en" manifest="/manifest.appcache">
More info about offline application cache that helps me a lot can be found here.

how to fill html file using ruby script

I have a html file has the general design (some div's) and I need to fill this div's with some html code Using ruby script.
any suggests?
example
I have page.html
<html>
<title>html Page</title>
<body>
<div id="main">
</div>
<div id="side">
</div>
</body>
</html>
and a ruby script inside it i collect some data and doing some kind of processing on it and i want to present it in a nice format**
so I want to set the div which it's id=main with some html code to be like this
<html>
<title>html Page</title>
<body>
<div id="main">
<h1>you have 30 files in games folder</h1>
</div>
<div id="side">
</div>
</body>
</html>
** why i don't use ROR? because I don't want to build a web site I just need to build a desktop tool but it's presentation layer is html code interpreted by browser to avoid working with graphics libraries
my problem isn't "how can I write to this html file" I can handle it.
my problem that If I want to create a table in the html file inside main div
I will wrote the whole html code inside the ruby script to print it to the html file, is there any lib or gem that i can tell it that I want a table with 3 rows and 2 columns and it generates the html code?
I historically have used ERB and REXML for things like this, since they both ship with Ruby (removing gem dependencies). You can combine one XML file (content) with one .erb file (for layout) and get simple merging. Here's a script I wrote for this (most of which is argument handling and extending REXML with some convenience methods):
USAGE = <<ENDUSAGE
Usage:
rubygen source_xml [-t template_file] [-o output_file]
-t,--template The ERB template file to merge (default: xml_name.erb)
-o,--output The output file name to write (default: template.txt)
If the template_file is named "somefile_XXX.yyy",
the output_file will default instead to "somefile.XXX"
ENDUSAGE
ARGS = {}
UNFLAGGED_ARGS = [ :source_xml ]
next_arg = UNFLAGGED_ARGS.first
ARGV.each{ |arg|
case arg
when '-t','--template'
next_arg = :template_file
when '-o','--output'
next_arg = :output_file
else
if next_arg
ARGS[next_arg] = arg
UNFLAGGED_ARGS.delete( next_arg )
end
next_arg = UNFLAGGED_ARGS.first
end
}
if !ARGS[:source_xml]
puts USAGE
exit
end
extension_match = /\.[^.]+$/
template_match = /_([^._]+)\.[^.]+$/
xml_file = ARGS[ :source_xml ]
template_file = ARGS[ :template_file] || xml_file.sub( extension_match, '.erb' )
output_file = ARGS[ :output_file ] || ( ( template_file =~ template_match ) ? template_file.sub( template_match, '.\\1' ) : template_file.sub( extension_match, '.txt' ) )
require 'rexml/document'
include REXML
class REXML::Element
# Find all descendant nodes with a specified tag name and/or attributes
def find_all( tag_name='*', attributes_to_match={} )
self.each_element( ".//#{REXML::Element.xpathfor(tag_name,attributes_to_match)}" ){}
end
# Find all child nodes with a specified tag name and/or attributes
def kids( tag_name='*', attributes_to_match={} )
self.each_element( "./#{REXML::Element.xpathfor(tag_name,attributes_to_match)}" ){}
end
def self.xpathfor( tag_name='*', attributes_to_match={} )
out = "#{tag_name}"
unless attributes_to_match.empty?
out << "["
out << attributes_to_match.map{ |key,val|
if val == :not_empty
"##{key}"
else
"##{key}='#{val}'"
end
}.join( ' and ' )
out << "]"
end
out
end
# A hash to tag extra data onto a node during processing
def _mydata
#_mydata ||= {}
end
end
start_time = Time.new
#xmldoc = Document.new( IO.read( xml_file ), :ignore_whitespace_nodes => :all )
#root = #xmldoc.root
#root = #root.first if #root.is_a?( Array )
end_time = Time.new
puts "%.2fs to parse XML file (#{xml_file})" % ( end_time - start_time )
require 'erb'
File.open( output_file, 'w' ){ |o|
start_time = Time.new
output_code = ERB.new( IO.read( template_file ), nil, '>', 'output' ).result( binding )
end_time = Time.new
puts "%.2fs to run template (#{template_file})" % ( end_time - start_time )
start_time = Time.new
o << output_code
}
end_time = Time.new
puts "%.2fs to write output (#{output_file})" % ( end_time - start_time )
puts " "
This can be used for HTML or automated source code generation alike.
However, these days I would advocate using Haml and Nokogiri (if you want structured XML markup) or YAML (if you want simple-to-edit content), as these will make your markup cleaner and your template logic simpler.
Edit: Here's a simpler file that merges YAML with Haml. The last four lines do all the work:
#!/usr/bin/env ruby
require 'yaml'; require 'haml'; require 'trollop'
EXTENSION = /\.[^.]+$/
opts = Trollop.options do
banner "Usage:\nyamlhaml [opts] <sourcefile.yaml>"
opt :haml, "The Haml file to use (default: sourcefile.haml)", type:String
opt :output, "The file to create (default: sourcefile.html)", type:String
end
opts[:source] = ARGV.shift
Trollop.die "Please specify an input Yaml file" unless opts[:source]
Trollop.die "Could not find #{opts[:source]}" unless File.exist?(opts[:source])
opts[:haml] ||= opts[:source].sub( EXTENSION, '.haml' )
opts[:output] ||= opts[:source].sub( EXTENSION, '.html' )
Trollop.die "Could not find #{opts[:haml]}" unless File.exist?(opts[:haml])
#data = YAML.load(IO.read(opts[:source]))
File.open( opts[:output], 'w' ) do |output|
output << Haml::Engine.new(IO.read(opts[:haml])).render(self)
end
Here's a sample YAML file:
title: Hello World
main: "<h1>you have 30 files in games folder</h1>"
side: "I dunno, something goes here."
...and a sample Haml file:
!!! 5
%html
%head
%title= #data['title']
%body
#main= #data['main']
#side= #data['side']
...and finally the HTML they produce:
<!DOCTYPE html>
<html>
<head>
<title>Hello World</title>
</head>
<body>
<div id='main'><h1>you have 30 files in games folder</h1></div>
<div id='side'>I dunno, something goes here.</div>
</body>
</html>
Are you trying to create a dynamic website? For that use Rails.
Are you trying to create a static website? Something like Jekyll is probably best.
Are you trying to to just create some some simple .html files you can FTP up somewhere? Jekyll might be a good option or even hand coding a quick little HTML generator might be a better option.
UPDATE:
Is this what you are looking for?
hash = {
:games => "you have 30 files in games folder",
:puppies => "you have 12 puppies in your pocket",
:pictures => "You have 9 files in pictures folder",
}
array = [
['run','x','y'],
[1,10,3],
[2,12,9],
[3,14,7],
]
hash.each do |key, value|
myfile = File.new("#{key}.html", "w+")
myfile.puts "<html>"
myfile.puts "<title>html Page</title>"
myfile.puts "<body>"
myfile.puts "<div id=\"main\">"
myfile.puts "<h1>#{value}</h1>"
myfile.puts "<table border=\"1\">"
array.each do |row|
myfile.puts "<tr>"
row.each do |cell|
myfile.puts "<td> #{cell} </td>"
end
myfile.puts "<tr>"
end
myfile.puts "</div>"
myfile.puts "<div id=\"side\">"
myfile.puts "</div>"
myfile.puts "</body>"
myfile.puts "</html>"
end
Continuing from #Phrogz's work, the ERB idea is a great idea. I was able to use it to build a simple Rake script that does the work for me. I find this approach to be a little easier.
rakefile.rb
task :default => :generate
task :generate do
require 'erb'
template_file = "page.erb"
output_file = "page.html"
File.open(output_file, 'w') do |o|
puts "Processing file: #{template_file}"
o << ERB.new( IO.read( template_file ), nil, '>', 'output' ).result( binding )
end
end
def render(file)
puts "Rendering file: #{file}"
IO.read(file)
end
$game_count = 30
def game_count
puts "Rendering game count: #{$game_count}"
$game_count
end
page.erb
<html>
<title>html Page</title>
<body>
<div id="main">
<h1>you have <%= game_count %> files in games folder</h1>
</div>
<div id="side">
<%= render "side.html" %>
</div>
</body>
</html>
side.html
<ul class="side">
<li>Side item 1</li>
<li>Side item 2</li>
</ul>
Running it
$ rake
Processing file: page.erb
Rendering game count: 30
Rendering file: side.html
Newly created file page.html
<html>
<title>html Page</title>
<body>
<div id="main">
<h1>you have 30 files in games folder</h1>
</div>
<div id="side">
<ul class="side">
<li>Side item 1</li>
<li>Side item 2</li>
</ul>
</div>
</body>
</html>

FeedTools behaves differently with JRuby

With Ruby 1.8, FeedTools is able to get and parse rss/atom feed links given a non-feed link. For eg:
ruby-1.8.7-p174 > f = FeedTools::Feed.open("http://techcrunch.com/")
=> #<FeedTools::Feed:0xc99cf8 URL:http://feeds.feedburner.com/TechCrunch>
ruby-1.8.7-p174 > f.title
=> "TechCrunch"
Whereas, with JRuby 1.5.2, FeedTools is unable to get and parse rss/atom feed links given a non-feed link. For eg:
jruby-1.5.2 > f = FeedTools::Feed.open("http://techcrunch.com/")
=> #<FeedTools::Feed:0x1206 URL:http://techcrunch.com/>
jruby-1.5.2 > f.title
=> nil
At times, it also gives the following error:
FeedTools::FeedAccessError: [URL] does
not appear to be a feed.
Any ideas on how I can get FeedTools to work with JRuby?
There seems to be a bug in the feedtools gem. In the method to locate feed links with a given mime type, replace 'lambda' with 'Proc.new' to return from the method from inside the proc when the feed link is found.
--- a/feedtools-0.2.29/lib/feed_tools/helpers/html_helper.rb
+++ b/feedtools-0.2.29/lib/feed_tools/helpers/html_helper.rb
## -620,7 +620,7 ##
end
end
get_link_nodes.call(document.root)
- process_link_nodes = lambda do |links|
+ process_link_nodes = Proc.new do |links|
for link in links
next unless link.kind_of?(REXML::Element)
if link.attributes['type'].to_s.strip.downcase ==