Save Content of Ace in Rails

As I told you we are making an Editor. So we have to save the file after editing.

There are a number of ways to do this. I am doing it using Ajax.
For this, we need
1. filename or location
2. Content
to save a file. But the twist is we are using Ajax editor. Ace editor is a javascript editor so it performs operations only in javascript file
So what I have done is to Get content and location from the app and then send it to the controller using Ajax. Here, Ajax play’s a very important role. Let’s be more technical!

first of all, save button

create a save button in HTML with attribute class=”save button”

then javascript
$('.save-button').click(function(){
var name = "editor-" + $("#tabs-editor> .current").attr("id"); // This will store the location of editor
var editor=ace.edit(name);
var content= editor.getSession().getValue();// This will get the content of the eidtor which is editted
$file.push($("#tabs-editor > .current").attr("id")) // This is simple editor storing all files location which is edited
$.ajax({ // Ajax call
url: "filedata", //url
type: "post", //method
data: { //data to be sent
"file" :$("#tabs-editor> .current").attr("id"),
"content" : content
},
dataType: JSON,
success: function(data){ //On success
alert('successfully');
}
});
});

We will attach data attribute only when we have to send data to the controller

Now Routes will get the url “filedata” and perform the action which is specified to it by transferring control in controller

for that let’s edit routes.rb

post 'gitrepos/filedata', to: 'gitrepos#filedata'

then here controller is gitrepos
the action is filedata

def filedata
name = {}
request.POST.each do |key, value|
name[key] = value
end
puts name['file']
f = File.open(name['file'], 'w')
f.write(name['content'])
f.close
end

That’s it

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s